Serving over HTTP
Everything so far called graphql() directly. A real API wraps that call in an HTTP server. The GraphQL over HTTP specification (from the GraphQL Foundation) describes the conventions every server and client follows, so any client works with any server.
The request
There is usually one endpoint, conventionally /graphql. A request carries up to three parameters:
| Parameter | Meaning |
|---|---|
query |
the document text (required) |
variables |
JSON object of variable values (optional) |
operationName |
which operation to run if there are several (optional) |
With POST they travel as JSON in the body:
POST /graphql HTTP/1.1
Content-Type: application/json
Accept: application/graphql-response+json, application/json
{"query":"query Book($id: ID!) { book(id: $id) { title } }","variables":{"id":"1"},"operationName":"Book"}With GET they go in the URL, which allows HTTP caching, but GET may only run queries, never mutations (a GET must not change anything).
The response
The body is the familiar { "data": …, "errors": … } JSON. With the modern media type application/graphql-response+json, the status code tells clients what happened:
| Situation | Status |
|---|---|
| executed (even with field errors) | 200 |
| invalid JSON, syntax or validation error | 400 |
| mutation via GET | 405 (Method Not Allowed) |
| not authenticated (if the whole API requires it) | 401 |
A handler, without a server
The core of every GraphQL HTTP server is a function from a request to a response. Here it is, tested with fake requests:
import { buildSchema, parse, validate, execute, getOperationAST, GraphQLError } from 'graphql';
const schema = buildSchema(`
type Book { id: ID!, title: String! }
type Query { book(id: ID!): Book }
type Mutation { rename(id: ID!, title: String!): Book }
`);
const books = { 1: { id: '1', title: 'Emma' } };
const rootValue = {
book: ({ id }) => books[id],
rename: ({ id, title }) => Object.assign(books[id], { title }),
};
async function handleGraphQL(req) {
let params;
if (req.method === 'GET') {
const url = new URL(req.url, 'http://localhost');
params = {
query: url.searchParams.get('query'),
variables: JSON.parse(url.searchParams.get('variables') ?? 'null'),
operationName: url.searchParams.get('operationName'),
};
} else if (req.method === 'POST') {
try {
params = JSON.parse(req.body);
} catch {
return { status: 400, body: { errors: [{ message: 'Body is not valid JSON' }] } };
}
} else {
return { status: 405, body: { errors: [{ message: 'Only GET and POST are supported' }] } };
}
let document;
try {
document = parse(params.query ?? '');
} catch (syntaxError) {
return { status: 400, body: { errors: [syntaxError.toJSON()] } };
}
const validationErrors = validate(schema, document);
if (validationErrors.length) return { status: 400, body: { errors: validationErrors.map((e) => e.toJSON()) } };
const operation = getOperationAST(document, params.operationName);
if (req.method === 'GET' && operation?.operation === 'mutation') {
return { status: 405, body: { errors: [{ message: 'Mutations must use POST' }] } };
}
const contextValue = { user: req.headers?.authorization ?? null };
const result = await execute({
schema, document, rootValue, contextValue,
variableValues: params.variables, operationName: params.operationName,
});
return { status: 200, body: JSON.parse(JSON.stringify(result)) };
}
const requests = [
{ method: 'POST', body: JSON.stringify({ query: 'query B($id: ID!) { book(id: $id) { title } }', variables: { id: '1' } }) },
{ method: 'GET', url: '/graphql?query=' + encodeURIComponent('{ book(id: 1) { id title } }') },
{ method: 'GET', url: '/graphql?query=' + encodeURIComponent('mutation { rename(id: 1, title: "X") { title } }') },
{ method: 'POST', body: '{"query": "{ book(id: 1) { title } "}' },
{ method: 'POST', body: '{ not json' },
{ method: 'POST', body: JSON.stringify({ query: 'mutation { rename(id: 1, title: "Emma (annotated)") { title } }' }) },
];
for (const req of requests) {
const res = await handleGraphQL(req);
console.log(req.method.padEnd(4), res.status, JSON.stringify(res.body));
}POST 200 {"data":{"book":{"title":"Emma"}}}
GET 200 {"data":{"book":{"id":"1","title":"Emma"}}}
GET 405 {"errors":[{"message":"Mutations must use POST"}]}
POST 400 {"errors":[{"message":"Syntax Error: Expected Name, found <EOF>.","locations":[{"line":1,"column":25}]}]}
POST 400 {"errors":[{"message":"Body is not valid JSON"}]}
POST 200 {"data":{"rename":{"title":"Emma (annotated)"}}}
Real servers add more: content negotiation, CORS, body size limits, authentication middleware, the GraphiQL IDE page, logging and metrics. That's why you normally use a library.
Popular servers (JavaScript)
GraphQL Yoga (by The Guild) follows the GraphQL over HTTP spec closely and runs on Node, Deno, Bun and edge runtimes:
import { createServer } from 'node:http';
import { createSchema, createYoga } from 'graphql-yoga';
const yoga = createYoga({
schema: createSchema({
typeDefs: /* GraphQL */ `type Query { hello(name: String): String! }`,
resolvers: { Query: { hello: (_, { name }) => `Hello, ${name ?? 'world'}!` } },
}),
context: ({ request }) => ({ token: request.headers.get('authorization') }),
});
createServer(yoga).listen(4000, () => console.log('http://localhost:4000/graphql'));Apollo Server is the most widely deployed:
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
const server = new ApolloServer({
typeDefs: `type Query { hello: String! }`,
resolvers: { Query: { hello: () => 'Hello from Apollo' } },
});
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
context: async ({ req }) => ({ user: await userFromToken(req.headers.authorization) }),
});graphql-http is the reference implementation of the spec, with adapters for Express, Fastify and others:
import express from 'express';
import { createHandler } from 'graphql-http/lib/use/express';
const app = express();
app.all('/graphql', createHandler({ schema, rootValue, context: (req) => ({ user: req.raw.user }) }));
app.listen(4000);In other languages: graphql-java / Spring for GraphQL, Strawberry and Graphene (Python), Hot Chocolate (.NET), gqlgen (Go), async-graphql (Rust).
Calling it from a client
You don't need a special library to call a GraphQL API: it's a fetch with JSON.
async function gql(query, variables) {
const response = await fetch('https://api.example.com/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ query, variables }),
});
const { data, errors } = await response.json();
if (errors?.length) console.warn(errors.map((e) => e.message));
return data;
}
const data = await gql('query Book($id: ID!) { book(id: $id) { title } }', { id: '1' });Client libraries (Apollo Client, urql, Relay, graphql-request) add normalized caching, React hooks, pagination helpers and code generation of TypeScript types from your queries.
Tip: Even for internal tools, enable GraphiQL (or Apollo Sandbox) in development. Its schema explorer and autocomplete, both powered by introspection, make exploring an API dramatically faster.
Test yourself
Which HTTP method may NOT be used for mutations?
- POST
- GET
- Both are fine
- Neither
What status does a spec-compliant server return when a query fails validation?
- 200
- 400
- 404
- 500
Which three parameters make up a GraphQL HTTP request?
query,variables,operationNameurl,method,bodyschema,rootValue,contexttype,fields,args