GraphQL over HTTP

Beginner · 4 min

See what actually crosses the wire in a GraphQL request, from the JSON body of a POST to GET queries, status codes and the response media type.

Before thisYour first query in GraphiQL

Jamie Barton · 4 min

GraphQL over HTTP

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jamie BartonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A GraphQL request is an ordinary HTTP request to one endpoint, usually POST with a JSON body holding query, variables, and operationName.
  • Queries can also be sent with GET and URL parameters; mutations must not be, and Yoga answers a GET mutation with 405 Method Not Allowed.
  • The response is JSON with a data key, an errors key, or both; field errors are a normal part of a 200 response.
  • With the Accept header application/graphql-response+json a server can use real HTTP status codes for requests that fail before execution, such as 400 for a validation error.
  • Any HTTP client works: fetch, curl, or a GraphQL client library, which mostly adds caching and convenience on top.

One endpoint, one kind of request

In REST the URL and the verb carry the intent: DELETE /books/10 means what it says. A GraphQL server turns that around. There is normally a single URL, often /graphql, and the intent is inside the body. HTTP is only the courier.

The GraphQL specification does not pick HTTP. There is a separate community specification called GraphQL over HTTP that spells out the conventions, and servers like GraphQL Yoga follow it. This lesson uses Yoga 6.1.0 and graphql 17.1.0, and every response below is real output from them.

Start the server from the previous lesson (node server.mjs, listening on port 4000).

The POST request

curl -i localhost:4000/graphql \
  -H 'content-type: application/json' \
  -d '{"query":"query Q($id: ID!){ book(id:$id){ title } }","variables":{"id":"12"},"operationName":"Q"}'

The response, trimmed:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{"data":{"book":{"title":"Cosmos"}}}

Three keys make up the body:

  • query, the text of the GraphQL document.
  • variables, a JSON object of values, so you never build query strings by hand. See variables and operation names.
  • operationName, which picks one operation when the document contains several.

The same request from JavaScript, which is all a “GraphQL client” fundamentally does:

const res = await fetch('http://localhost:4000/graphql', {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    accept: 'application/graphql-response+json',
  },
  body: JSON.stringify({
    query: 'query GetBook($id: ID!) { book(id: $id) { title year } }',
    variables: { id: '12' },
    operationName: 'GetBook',
  }),
})
console.log(res.status, res.headers.get('content-type'))
console.log(await res.json())

Output on my run:

200 application/graphql-response+json; charset=utf-8
{ data: { book: { title: 'Cosmos', year: 1980 } } }

That is the whole protocol for a query. Calling GraphQL with fetch later builds a small typed wrapper around it.

GET for queries

A query can also travel in the URL:

curl 'localhost:4000/graphql?query=%7Bbooks(limit:1)%7Btitle%7D%7D'
# {"data":{"books":[{"title":"The Dispossessed"}]}}

GET is safe and cacheable by definition, so servers only accept queries this way. Try ?query=mutation{x} and Yoga replies 405 Method Not Allowed with Allow: POST and the message “Can only perform a mutation operation from a POST request.” Long queries make long URLs, which is one reason persisted queries exist (persisted queries).

Reading the response

A successful response has a data key shaped like your query. A failed one has errors, each with a message, usually locations, and a path when it came from a field. You can have both: some fields resolved, one failed and is null. Resolvers are covered in errors and partial responses, but the point for HTTP is that a field error does not change the status. I asked for book(id: "99"), which does not exist, and got 200 with {"data":{"book":null}}.

Status codes: the part that surprises people

Historically GraphQL servers returned 200 for almost everything, even a malformed query, because the HTTP request itself was fine. That makes monitoring awkward: your dashboards see 200s while clients see errors. Two media types matter.

Ask for a bad field with the default application/json:

HTTP/1.1 200 OK
{"errors":[{"message":"Cannot query field \"nope\" on type \"Book\".","locations":[{"line":1,"column":19}],"extensions":{"code":"GRAPHQL_VALIDATION_FAILED"}}]}

Now send the header Accept: application/graphql-response+json:

HTTP/1.1 400 Bad Request
Content-Type: application/graphql-response+json; charset=utf-8
{"errors":[{"message":"Cannot query field \"nope\" on type \"Book\".", ...

I ran both. With the newer media type the server uses status codes that reflect what happened: a document that fails to parse or validate is a 400, and 200 means execution ran, possibly with field errors. Other cases I saw: a document with two operations and no operationName is a 400 (“Could not determine what operation to execute.”), and a PUT is a 405.

Practical advice: send that Accept header from your clients when your server supports it, and never treat 200 as meaning “no errors”. Check the errors key.

Form posts and other bodies

Yoga also accepted application/x-www-form-urlencoded with a query field. JSON is the default, and the one every client library uses. GraphQL file uploads use multipart/form-data under a separate convention and are out of scope here.

What the video covers

Jamie Barton’s “GraphQL over fetch API” is under four minutes, published in October 2021. Its description says it explores using the fetch API to make a request to a GraphQL API. I could not read a transcript, so I do not know how much it says about GET, status codes, or the response media types; the sections above on those come from my own runs and are meant to fill that in. There is no runner-up for this exact topic, which is why deeper is empty.

Where this fits

You now know a GraphQL call is a plain request. What surrounds it, in servers, clients, and tools, is the ecosystem. Next: the GraphQL ecosystem.

Check yourself

  1. 01What are the three keys of the standard JSON request body?

    query is the document text, variables is an object of values for the operation's variables, and operationName picks which operation to run when the document has more than one.

  2. 02Why is a GraphQL mutation rejected over GET?

    GET is meant to be safe and cacheable, and a mutation changes state, so servers require POST for it.

  3. 03How do the two response media types differ for an invalid query?

    With plain application/json Yoga answers 200 with an errors array, while with application/graphql-response+json it answers 400 Bad Request, because the request never reached execution.

  4. 04A query returns data with one field null and an errors entry for that field. What is the HTTP status likely to be?

    200, since execution happened and the response carries a partial result, so clients must read the errors key rather than rely on the status alone.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark