How to Test GraphQL API: Simple Steps and Examples
To test a
GraphQL API, send queries or mutations to the API endpoint and check the JSON response for expected data. You can use tools like curl, GraphiQL, or testing libraries such as Apollo Client to automate and verify results.Syntax
A GraphQL test request usually includes a query or mutation string sent as JSON to the API endpoint. The key parts are:
query: The GraphQL operation to fetch or modify data.variables: Optional dynamic values used inside the query.operationName: Optional name if multiple operations exist.
The server responds with JSON containing data or errors.
json
{
"query": "query GetUser($id: ID!) { user(id: $id) { id name } }",
"variables": { "id": "123" }
}Example
This example shows how to test a GraphQL API using curl to send a query and check the response.
bash
curl -X POST https://example.com/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query { user(id: \"1\") { id name email } }" }'
Output
{
"data": {
"user": {
"id": "1",
"name": "Alice",
"email": "alice@example.com"
}
}
}
Common Pitfalls
Common mistakes when testing GraphQL APIs include:
- Not setting the
Content-Typeheader toapplication/json. - Sending queries as plain text instead of JSON.
- Ignoring errors returned in the response.
- Not using variables properly, causing query failures.
Always check both data and errors fields in the response.
json
Wrong:
{
"query": "{ user(id: \"1\") { id name } }"
}
Right:
{
"query": "query GetUser($id: ID!) { user(id: $id) { id name } }",
"variables": { "id": "1" }
}Quick Reference
Tips for effective GraphQL API testing:
- Use tools like
GraphiQLorInsomniafor manual testing. - Automate tests with libraries like
Apollo ClientorJest. - Validate both
dataanderrorsin responses. - Use variables to keep queries flexible and reusable.
Key Takeaways
Send GraphQL queries or mutations as JSON with proper headers to test the API.
Use tools like curl, GraphiQL, or Apollo Client for manual and automated testing.
Always check the response for both data and errors to verify correctness.
Use variables in queries to make tests flexible and maintainable.
Avoid common mistakes like missing headers or incorrect query formatting.