cURL by Example: GraphQL Request
Execute a GraphQL query. GraphQL requests are typically POST requests with a JSON body containing the query.
Code
# Simple GraphQL Query
curl -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ user(id: 1) { name email } }"}'
# GraphQL Query with Variables
curl -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{"query": "query getUser($id: ID!) { user(id: $id) { name } }", "variables": {"id": "1"}}'Explanation
GraphQL uses a different approach than REST APIs. Instead of having multiple endpoints, GraphQL typically has a single endpoint that accepts POST requests with a JSON body containing your query.
The JSON body structure for GraphQL requests:
query: Contains the GraphQL query stringvariables: Optional object containing query parametersoperationName: Optional name for the operation when multiple queries exist
Escaping quotes in the command line can get messy quickly. For complex queries, it's better to save your GraphQL query in a file and use -d @query.json. This keeps your command readable and makes it easier to format the JSON properly.
Variables help you reuse queries with different parameters. Instead of embedding values directly in the query string, you define them as variables and pass actual values in the variables field. This is similar to prepared statements in SQL.
Code Breakdown
-X POST is the standard method for GraphQL.Content-Type: application/json is required.query field contains the GraphQL syntax string.
