API TESTING

Testing GraphQL APIs: What's Different From REST (and Agents)

If you've written tests against REST APIs and then joined a GraphQL project, the mental model stops working almost immediately. There's one endpoint. Nearly every request is a POST. The server often returns HTTP 200 when something went wrong. The habits that served you in REST, checking status codes, mapping operations to methods, treating a 4xx as failure, don't transfer cleanly, and rebuilding them takes longer than teams expect.

GraphQL also brings an agentic twist. Its schema is self-describing, which makes it attractive to expose to LLM agents, sometimes directly and sometimes through an MCP server: the agent reads the schema and writes its own queries. That means queries you never wrote and never tested will hit your server, and some of them will be deeply nested or expensive. On the other side, coding agents writing your GraphQL tests tend to request every field in sight and assert on whatever comes back.

In this article I'll cover the concrete differences when testing GraphQL versus REST, show them in Python test code, and finish with what changes when agents write the queries, either in your test suite or in production. If you want a refresher on REST status codes and methods first, the API testing guide covers that baseline.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Status codes don't tell you enough

In REST, a 404 means not found and a 500 means the server failed, and assertions can lean on that. Many GraphQL servers return 200 for any request they could parse and execute, and put failures in a top-level errors array:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "data": {"user": null},
  "errors": [
    {"message": "User not found", "locations": [{"line": 2, "column": 3}], "path": ["user"]}
  ]
}

A test that checks only status_code == 200 passes on that. Servers differ at the edges: some return 400 for a malformed query or 401 for a missing token at the HTTP layer, and newer servers following the GraphQL-over-HTTP conventions may use non-200 codes more often. So keep the status check, but never let it be the only one. I put both in one helper that every test uses:

import os

import requests

GRAPHQL_URL = os.environ["GRAPHQL_URL"]


def gql(query: str, variables: dict | None = None, headers: dict | None = None) -> dict:
    response = requests.post(GRAPHQL_URL, json={"query": query, "variables": variables or {}},
                             headers=headers or {}, timeout=10)
    assert response.status_code == 200, f"HTTP {response.status_code}: {response.text[:500]}"
    return response.json()


def gql_data(query: str, variables: dict | None = None, headers: dict | None = None) -> dict:
    body = gql(query, variables, headers)
    assert not body.get("errors"), f"GraphQL errors: {body['errors']}"
    return body["data"]

gql_data is for happy paths and fails loudly on any GraphQL error. gql returns the raw body for tests that expect an error. Centralising this also means one place to change if your server's error format shifts. The same trap exists in plain REST APIs, as I describe in testing API responses that embed errors inside a 200.

Query what your clients actually query

In REST the server fixes the response shape. In GraphQL the client chooses fields, which creates a testing problem REST doesn't have: tests can quietly stop covering the fields that matter. Requesting every field couples tests to the whole schema; requesting only id validates almost nothing. I write test queries that mirror real client operations, and assert on every field requested:

GET_USER = """
query GetUser($id: ID!) {
  user(id: $id) {
    id
    name
    email
  }
}
"""


def test_get_user_returns_client_fields(seeded_user):
    user = gql_data(GET_USER, {"id": seeded_user.id})["user"]
    assert user["id"] == seeded_user.id
    assert user["name"] == seeded_user.name
    assert user["email"] == seeded_user.email

Expected values come from a seeded user, not from the response itself. Keeping operations in .graphql files, ideally the same files the client uses, makes them reusable, easier to diff and lintable:

from pathlib import Path


def load_operation(name: str) -> str:
    return (Path(__file__).parent / "operations" / name).read_text()

If a field the client depends on is renamed or removed, a test built from the client's own operation fails, because the server rejects a query for a field that no longer exists. That's a cheap early warning for schema drift, and it pairs well with the approach in API contract testing.

Mutations, auth errors and partial results

GraphQL allows partial success: one response can carry data for some fields and errors for others. Negative tests should expect the error explicitly and assert on what it says. Many servers put a machine-readable code in extensions.code, for example UNAUTHENTICATED; that's a widespread convention rather than part of the core spec, so check what yours returns and assert on that instead of matching message text:

CREATE_POST = load_operation("create_post.graphql")


def test_create_post_requires_auth():
    body = gql(CREATE_POST, {"input": {"title": "No auth", "body": "Should fail"}})
    assert body.get("errors"), "expected an error for an unauthenticated mutation"
    codes = {e.get("extensions", {}).get("code") for e in body["errors"]}
    assert "UNAUTHENTICATED" in codes, f"unexpected errors: {body['errors']}"
    assert not (body.get("data") or {}).get("createPost"), "mutation must not return a post"

If your server rejects unauthenticated requests with an HTTP 401 instead, assert that. Either way, pin the behaviour. A few more habits for mutations:

  • Assert on returned data, not just the absence of errors. A mutation returning null for the created object is a bug.
  • Read back what you wrote. Follow a mutation with a query to confirm the state actually changed.
  • Test the validation layer. A missing non-null argument should be rejected before any resolver runs; one test per important input type confirms the schema says what you think.
  • Log the full request and response on failure. GraphQL detail lives in the body, so a bare assertion error in CI tells you almost nothing.

When agents write the queries

If you expose your GraphQL API to an LLM agent, the set of queries your server must handle safely is no longer the set your clients send. The agent composes its own from the schema. A few tests become essential:

  • Depth and cost limits. Send a deeply nested query, such as users to posts to comments to authors and back, and assert the server rejects it with a clear error rather than timing out. Most GraphQL servers support depth or complexity limits through configuration or plugins; test that yours is turned on.
  • Authorization per field, not per operation. An agent acting for a user may request fields that user can't see. Run a maximal query with that user's token and assert restricted fields come back null with an authorization error.
  • Errors an agent can act on. A validation error naming the bad field lets the agent fix its query. "Internal server error" sends it into a retry loop.
DEEP_QUERY = """
{ users { posts { comments { author { posts { comments { author { id } } } } } } } }
"""


def test_overly_deep_query_is_rejected(member_headers):
    body = gql(DEEP_QUERY, headers=member_headers)
    assert body.get("errors"), "deep query should be refused"
    assert body.get("data") is None

If your server rejects this at the HTTP layer with a 400 instead, adjust the helper call. The important thing is that the limit exists and is tested.

For coding agents writing your GraphQL tests, the guidance I put in .github/copilot-instructions.md (or an equivalent agent file) is short: use gql_data for happy paths and gql for expected errors; build tests from operations in the operations/ folder rather than inventing queries; take expected values from seeded fixtures, never from a live response. That keeps generated tests tied to what real clients do.

The mental shift

The change from REST isn't enormous, but it's real. Stop treating 200 as success, test the operations clients actually send, handle partial results deliberately, and if agents can write queries against your API, test the limits that protect it from queries nobody planned for. If you want to build an API suite end to end with GitHub Copilot as a pair, my API testing courses are a practical place to start.