GraphQL: basics and testing
GraphQL describes an API with a typed schema, usually with one endpoint where the client chooses the fields it needs. A response has data and errors keys, so it can be partial: a failed field becomes null, the rest of the data arrives, and status 200 says almost nothing. A test checks errors, their path and code, authorization at every field level, and limits on depth, complexity and aliases.
API · GraphQL
A query returned 200, the response has errors, yet some data is there. Is the test green or red?
A GraphQL test checks status === 200 and goes green. Meanwhile the response body contains "owner": null and an errors array with “Not authorized”. The client shows an empty owner name. REST habits do not work here: the status says almost nothing, and part of a response can be correct together with an error.
The lesson: how GraphQL is built, where errors live in it, what to check at field level and how to stop a client from bringing the server down with one query.
How it works and why it is designed so
GraphQL (the specification is on graphql.org) describes an API with a typed schema. The server usually has one endpoint, POST /graphql, and the client says in the query exactly which fields it needs. This solves two REST problems: over-fetching (more came than needed) and under-fetching (several requests were needed). There are three operations: query reads, mutation changes, subscription subscribes to events. Top-level mutation fields run serially, query fields may run in parallel.
{
"query": "query Account($id: ID!) { account(id: $id) { id balance owner { name } } }",
"variables": { "id": "42" }
}
The query and the variables travel separately: the client passes variables typed ($id: ID!) instead of gluing them into a string, which protects against injection into the query itself.
The response has the keys data and errors. The idea is that every field is resolved separately, and the failure of one need not cancel the rest. If a field could not be obtained, it becomes null and errors gets an entry with message, path (where exactly) and usually extensions with a code. If the field is declared non-null in the schema (String!), the null “bubbles up” to the nearest parent field that may be null, and a bigger chunk of data disappears.
{
"data": { "account": { "id": "42", "balance": 120.5, "owner": null } },
"errors": [
{
"message": "Not authorized to read owner",
"path": ["account", "owner"],
"extensions": { "code": "FORBIDDEN" }
}
]
}
Where the error lives: REST versus GraphQL
REST
The status says what happened: 403, 404, 422. The body describes details. One request, one result, success or error.
GraphQL
The transport is often 200. Success, error and a partial response are in the body: data + errors. An error is tied to a field through path.
Status-code rules in GraphQL over HTTP are evolving: the newer variant introduces the media type application/graphql-response+json, where an invalid request (a syntax error, a schema validation failure) gets 4xx. For application/json many servers still return 200 even in these cases. So fix the behaviour of a concrete API from its documentation, not from memory.
Example: from “checked the status” to checking data and errors
Before: a REST-style test. It passes even when the server returned an error (and it will fail on data.account if there is no data at all).
// before: REST habits
const res = await request.post('/graphql', { data: { query: ACCOUNT, variables: { id: '42' } } });
expect(res.status()).toBe(200); // true even when the query failed
expect((await res.json()).data.account.id).toBe('42');
After: a helper returns both the status and the body, and the test checks errors, path, data and the behaviour of the other fields. This is a “field-level authorization” case: access to account exists, but access to the nested owner must be forbidden.
async function gql(request: APIRequestContext, query: string, variables = {}, token = '') {
const res = await request.post('/graphql', {
headers: token ? { Authorization: 'Bearer ' + token } : {},
data: { query, variables },
});
return { status: res.status(), body: await res.json() };
}
test('owner field is forbidden for a non-owner, the rest still comes', async ({ request }) => {
const { body } = await gql(request, ACCOUNT, { id: '42' }, OTHER_USER_TOKEN);
expect(body.errors?.[0].path).toEqual(['account', 'owner']);
expect(body.data.account.owner).toBeNull();
});
Order of checks: first whether errors is there and whether the code in extensions matches; then data (fully null or partial); then that foreign data did not leak through a nested field. This is where BOLA (access to another user's object) hides most often: in REST the endpoint is authorized, in GraphQL every field and every nested relation must be.
What else to check
- Invalid requests: a syntax error, an unknown field, a variable of the wrong type, a missing required variable. Expected: a validation error with
errorsand withoutdata, not 500. - Nullability: a non-null field must not return
nullwithouterrors. - Introspection: a
__schemaquery shows the whole schema. For public production it is often disabled so as not to hand out a map of the API, and on a test environment it is handy for checking the contract.
curl -s -X POST "$BASE/graphql" -H "Content-Type: application/json" \
-d '{"query":"{ __schema { types { name } } }"}'
- Depth and complexity: recursive relations (
account→transfers→account→ …) allow a very deep query. The server must limit depth, complexity, result size or execution time.
// builds { account(id:"42") { transfers { account { transfers { account { id } } } } } }
const nest = (depth: number): string =>
depth === 0 ? 'id' : 'transfers { account { ' + nest(depth - 1) + ' } }';
const query = '{ account(id: "42") { ' + nest(12) + ' } }';
const { status, body } = await gql(request, query);
expect(status === 400 || body.errors?.length > 0).toBe(true); // rejected, not executed
- Aliases and batching: one query can call the same field many times under different names. This bypasses a rate limit that counts HTTP requests, for example when guessing a PIN or codes.
{ "query": "mutation { a1: login(pin: \"0001\") a2: login(pin: \"0002\") a3: login(pin: \"0003\") }" }
- N+1: a list query with nested fields can produce hundreds of database queries. It shows in response time as the number of items grows.
- Mutation: the same idempotency and validation requirements as in REST; variables are typed, but the business rules are checked by the server.
Limits and alternatives
- HTTP caching in GraphQL is harder: everything goes as
POSTto one URL, so CDN-level caching works worse. This is compensated by persisted queries and client caches. - Tools: Playwright
request.postor any HTTP client works; Postman and Insomnia have built-in schema support and autocomplete. For contracts the schema itself serves as the specification, and it is compared between versions. - Alternatives for different needs: REST (caching, simplicity), gRPC (internal services, binary protocol). GraphQL is best where many different clients want different slices of data.
- Subscriptions usually go over WebSocket, not a plain HTTP request, and are tested separately.
Common mistakes
- Checking only the status. An error and partial data hide in the body.
- Checking only
data. If a field isnullbecause of an error and the test does not look intoerrors, the bug goes unnoticed. - Authorizing only the top level. Nested fields open foreign objects.
- Not testing depth limits and aliases. One query is enough to load the server or bypass a rate limit.
- Relying on introspection in every environment: on production it may be absent.
Check yourself
A query returned 200, data.account.owner = null and errors has an entry with path: ["account","owner"]. What follows for the test?
Answer
This is a partial response: the owner field could not be obtained (for example, no permission) and the rest of the data is correct. The test must check errors, its path and the code in extensions, not just the status, and make sure foreign data did not land in other fields.
Why does a rate limit by the number of HTTP requests not protect GraphQL from code guessing?
Answer
One HTTP request can contain hundreds of calls to the same field under different aliases, and the server counts it as one. You need limits on complexity or the number of operations in a query, not only on the number of requests.
Why is it not enough in GraphQL to authorize the /graphql endpoint?
Answer
The client chooses the fields and nested relations itself, so one allowed query can reach data the user must not see (for example, account.owner of someone else's account). Permissions are checked in the resolvers of each field or relation.
data and errors, because a response can be partial. Middle/Senior: Separately I check authorization at field and nested-relation level (BOLA), nullability, depth and complexity limits, and aliases as a rate-limit bypass. Introspection is usually disabled on production, and I look for N+1 by how response time grows with the number of items.