Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Clients and Transport

GraphQL over HTTP

See exactly what a GraphQL request and response look like on the wire: POST bodies, GET for persisted queries, status codes, CORS, and WebSocket or SSE.

GraphQL the language says nothing about networks. In practice almost every API serves it over HTTP, and a community specification ("GraphQL over HTTP") describes the common conventions: which method to use, what the JSON body looks like, what content types and status codes to send. Knowing these conventions makes debugging much easier, because you can read a request in the browser's network tab or send one with curl.

No GraphQL server runs on this site, so the real calls below are read-only. The runnable example is a stand-in server function that takes the text of a request body and returns a response, so you can see the rules in action. It is not a real GraphQL engine: it only recognizes one hard-coded query.

One request, three parts

query The document text, or an ID.
variables A JSON object of values.
operationName Which operation to run.

Send them as JSON in a POST body.

1 / 2

The POST request

A query goes in the body of a POST to a single endpoint, usually /graphql:

Terminal
curl -X POST https://api.example.com/graphql \
  -H "Content-Type: application/json" \
  -H "Accept: application/graphql-response+json, application/json" \
  -d '{
    "query": "query Hello($id: ID!) { user(id: $id) { name } }",
    "variables": { "id": "1" },
    "operationName": "Hello"
  }'

The JSON body has up to three keys:

  • query (required): the document text.
  • variables (optional): a JSON object, as you saw in Variables and Directives.
  • operationName (optional, required only when the document contains several operations): which one to run.

Some servers accept an extensions key too. Persisted-query systems put the hash there or use an id key instead of query.

The response

The server answers with a JSON object. It always has data, errors, or both, as described in Your First Query and How Execution Works and How Errors Behave:

JSON
{
  "data": { "user": { "name": "Ada" } }
}

Two media types exist:

  • application/json: the long-standing type. Older servers answer with 200 OK even when the query had errors, because a GraphQL "error" is often just a partial result.
  • application/graphql-response+json: the newer type from the HTTP specification. The client says it understands it in the Accept header. With it, servers use meaningful status codes.

Status codes

Conventions differ between the two types, so check your server's documentation. The ones you should expect:

Situation Typical status
Query ran (even with some field errors) 200
Malformed JSON, or the document cannot be parsed 400
Validation errors (unknown field, wrong type) 400 with the newer type; often 200 with the older one
Not authenticated (handled in HTTP middleware) 401
Not allowed to use the API at all 403
Rate limited 429
Unexpected server crash 500

Your client code should therefore look at both the status and the body: a network failure and a 500 mean "no GraphQL result", while a 200 may still carry errors.

GET requests

Queries (not mutations) can also use GET, with the pieces in the URL:

TEXT
GET /graphql?query=%7Buser(id%3A%221%22)%7Bname%7D%7D&variables=...

The raw form gets long, so GET is mostly used with persisted queries: GET /graphql?id=7f3a9c&variables=.... That gives CDNs distinct, cacheable URLs (see Caching and Performance). Servers must refuse mutations over GET, because browsers, crawlers and prefetchers may repeat GET requests freely.

Headers and CORS

  • Content-Type: application/json on the request is required for POST.
  • Authorization: Bearer ... or a session cookie authenticates the caller. The server reads it in middleware before GraphQL runs (Authentication and Authorization).
  • If your page is on app.example.com and the API is on api.example.com, the browser sends a CORS preflight (an OPTIONS request) before the POST, because application/json is not a "simple" content type. The API must answer with matching Access-Control-Allow-Origin, Access-Control-Allow-Headers and Access-Control-Allow-Methods headers. A CORS error is a server configuration problem, not a GraphQL problem.
  • Treat cookies carefully: if you authenticate with cookies, use SameSite settings and CSRF protection, since a cross-site form could otherwise trigger a mutation.

A fetch-based client

A minimal client is only a few lines. This is read-only code, because it needs a real endpoint:

JavaScript
async function graphql(query, variables = {}, operationName) {
  const response = await fetch("/graphql", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/graphql-response+json, application/json",
    },
    body: JSON.stringify({ query, variables, operationName }),
  });

  const result = await response.json().catch(() => null);
  if (!result) {
    throw new Error("HTTP " + response.status + ": no GraphQL response");
  }
  if (result.errors?.length && !result.data) {
    throw new Error(result.errors[0].message);
  }
  return result; // may hold both data and errors (partial success)
}

Notice the order of checks: parse JSON first, then decide. A 400 from a validation failure still has a useful errors array in its body.

A stand-in server function

The function below plays the server's role: it receives the raw body text and the HTTP method, then returns a status and JSON. It checks the same things a real HTTP layer checks before the GraphQL engine runs. The "engine" is a lookup table with one query, to keep the focus on the transport rules.

JS A stand-in HTTP handler for GraphQL requests

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that a user that does not exist still returns 200 with "user": null: the query itself succeeded, and null is a legal answer for a nullable field. Only requests the server cannot process at all get a 4xx status.

The same function can be adapted into a tiny client test: call it directly, as you would in Testing GraphQL APIs, with no network.

JS Reading a response the careful way

Press Run (or Ctrl + Enter) to see the console output here.

No output.

WebSocket and SSE transports

Queries and mutations fit the request/response pattern of HTTP. Subscriptions need a long-lived connection, so they use another transport:

  • WebSocket, usually with the graphql-transport-ws subprotocol: the client opens a socket, sends a connection_init message (often with an auth token), then subscribe messages, and the server sends next messages for each event and a complete message when done.
  • Server-Sent Events (SSE): an ordinary HTTP response that stays open, with the server pushing event: next messages. It works through many proxies that dislike WebSockets, and it is one-directional, which is all a subscription needs.

You will build the event side in Subscriptions, Live Updates and File Uploads. Incremental delivery (@defer) uses a similar streamed HTTP response.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which JSON keys can a standard GraphQL POST body contain?

    query is required; variables and operationName are optional. Persisted-query systems may use an id or extensions instead of query.
  2. 2. A query asks for a user that does not exist, and the field is nullable. What does a typical server return?

    The GraphQL operation succeeded; null is a valid value for a nullable field. HTTP-level 4xx codes are for requests that could not be processed as GraphQL.
  3. 3. Why must a server refuse mutations sent with GET?

    GET is expected to be safe and repeatable. Allowing writes there would let prefetchers or cross-site links change data.
  4. 4. Why does a cross-origin GraphQL POST trigger a preflight request?

    Browsers send an OPTIONS preflight before cross-origin requests with non-simple content types, and the API must answer with the right CORS headers.

Summary

  • Queries and mutations normally use POST /graphql with a JSON body of query, variables and operationName.
  • Responses carry data, errors, or both; a 200 can still contain errors, so inspect the body.
  • The newer application/graphql-response+json type uses clearer status codes; always read the server's documentation.
  • GET is for queries only, mostly with persisted IDs so CDNs can cache them.
  • Authentication, CORS and rate limiting are HTTP concerns handled before GraphQL runs.
  • Subscriptions use WebSocket or SSE transports.
  • The handler here is a stand-in; real servers parse and validate full GraphQL documents.

Next: Clients, Apollo and Code Generation.