How to Make a GraphQL Request: Syntax and Example
To make a
GraphQL request, send a POST HTTP request to the GraphQL server endpoint with a JSON body containing a query string. The query defines what data you want, and the server responds with the requested data in JSON format.Syntax
A GraphQL request is usually sent as a POST request with a JSON body containing a query field. The query is a string that specifies the data you want. Optionally, you can include variables to pass dynamic values.
- query: The GraphQL query string.
- variables: Optional JSON object with variables for the query.
json
{
"query": "query { user(id: \"1\") { id name email } }",
"variables": null
}Example
This example shows how to make a GraphQL request using fetch in JavaScript to get a user's id, name, and email by id.
javascript
const query = ` query GetUser($id: ID!) { user(id: $id) { id name email } } `; const variables = { id: "1" }; fetch('https://example.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query, variables }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Output
{
"data": {
"user": {
"id": "1",
"name": "Alice",
"email": "alice@example.com"
}
}
}
Common Pitfalls
Common mistakes when making GraphQL requests include:
- Not setting the
Content-Typeheader toapplication/json. - Sending the query as plain text instead of JSON.
- Forgetting to stringify the request body.
- Not handling errors returned by the server.
Always check the server response for errors field.
javascript
/* Wrong way: Missing JSON stringify and headers */ fetch('https://example.com/graphql', { method: 'POST', body: '{ "query": "{ user { id } }" }' }); /* Right way: */ fetch('https://example.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: '{ user { id } }' }) });
Quick Reference
- Use POST requests with JSON body containing
queryand optionalvariables. - Set
Content-Typeheader toapplication/json. - Always stringify the request body.
- Check the response for
dataanderrors.
Key Takeaways
Send GraphQL requests as POST with JSON body containing a query string.
Always set the Content-Type header to application/json.
Use variables to pass dynamic values safely.
Check the response for errors to handle issues gracefully.
Stringify the request body before sending.