Web Development
Typed APIs from first query to schema design, execution, transports and pagination.
A path through GraphQL from the query language to how servers validate and execute operations, how schemas are designed, how subscriptions are delivered over HTTP, WebSockets and SSE, and which libraries to use on the server and the client. It suits frontend and backend developers who already know HTTP APIs. Each subject links the official specification or project documentation.
The subjects follow the roadmap.sh GraphQL roadmap.
GraphQL is a typed query language and runtime for APIs: the server publishes a schema, and each client asks for exactly the fields it needs in one request. It is a specification, not a product, so the same ideas apply whether you use Apollo, Yoga, graphql-java or Graphene.
A query language plus an execution engine defined by an open spec under the GraphQL Foundation. Clients send documents describing a tree of fields; the server validates them against its schema and returns JSON of the same shape.
Over-fetching and under-fetching from fixed REST endpoints, chains of round trips to assemble one screen, and loosely documented payloads. The schema doubles as a contract and live documentation via introspection.
Model your domain as connected types rather than as endpoints, name things after business concepts instead of database tables, and let clients walk relationships such as user { orders { items } }.
Components declare the data they need, often as colocated fragments; a client library sends the operations, normalises results into a cache and re-renders views when cached entities change.
The server owns the schema and a resolver per field, sitting in front of databases, REST services or other GraphQL APIs. Its main concerns are performance (N+1 queries), authorization per field and limiting query cost.
Queries are read operations. A query document selects fields on the root Query type and nests selections for every object it returns, so the response mirrors the request exactly. Learn the syntax pieces below and you can read any client code.
Operations starting with query (or a bare { ... } shorthand) that fetch data without side effects. Because they are side-effect free, servers may resolve sibling fields in parallel.
The unit of selection: every field you ask for maps to a field on a schema type and to a resolver. Object-typed fields need a sub-selection; scalar fields end the branch.
Named inputs on any field, such as user(id: "42") or avatar(size: 64). They are declared and typed in the schema, can have default values, and may be scalars, enums or input objects.
Rename a field in the result with small: avatar(size: 32). This is how you request the same field twice with different arguments in one selection set.
Annotations prefixed with @ that change execution or carry metadata. @include(if:) and @skip(if:) toggle fields from variables, @deprecated marks schema elements, and servers may define their own.
Declare typed parameters like query ($id: ID!) and pass values in a separate JSON object. Never build queries by string concatenation; variables keep documents static, cacheable and safe from injection.
Reusable selection sets declared with fragment X on Type and spread with ...X. Inline fragments (... on Droid) select fields that only exist on one member of an interface or union.
Mutations are write operations on the root Mutation type. They look like queries but signal side effects, and they return a payload you can select from so the client can update its cache without a second request.
Operations starting with mutation that create, update or delete data. A common convention is one input object argument and a payload type per mutation, e.g. createPost(input: CreatePostInput!): CreatePostPayload.
Unlike query fields, top-level mutation fields run one after another in document order, so two writes in one operation never race. Nested fields under each result still resolve normally.
The label after the keyword, as in mutation PublishPost. It is required when a document holds several operations and is what logs, tracing and persisted-query tooling use to tell requests apart.
Subscriptions are long-lived operations on the root Subscription type: the client subscribes once and the server pushes a result each time an event fires. They need a streaming transport, usually WebSockets or Server-Sent Events, and a pub/sub layer behind the resolvers.
A subscription operation must select exactly one root field. Each event runs the selection set again and yields a new response, so clients get exactly the fields they asked for per event.
The usual model: resolvers return an async iterator fed by a pub/sub system such as Redis or Postgres LISTEN/NOTIFY, and the server publishes events like messageAdded after writes.
An alternative where the client marks an ordinary query as live (often @live) and the server resends the result whenever the underlying data changes. Simpler for clients, but not part of the spec and harder to scale.
Proposed directives that let the server send a response in parts: @defer delays slow fragments and @stream delivers list items incrementally. Supported by some servers and clients, still not in a published spec edition.
The schema is the contract: every type, field, argument and root operation the API supports, usually written in Schema Definition Language (SDL). Clients validate and generate code against it, so design it for the consumers and evolve it by adding and deprecating rather than breaking.
Six named kinds — scalar, object, interface, union, enum and input object — plus the list and non-null wrappers. String! means never null; [Post!]! means a non-null list of non-null posts.
Leaf values: built-in Int (32-bit), Float, String, Boolean and ID, plus custom scalars such as DateTime or JSON whose serialization and parsing you implement on the server.
A closed set of named values like enum Role { ADMIN EDITOR VIEWER }. They validate input for free and document allowed values; adding a value can still break clients that switch exhaustively.
Named types with fields, each field having a type and optional arguments. Most of a schema is object types, and they are the only types that can implement interfaces.
The [T] wrapper. Combine it with ! deliberately: nullable items let one failed element become null instead of wiping the whole list. Large lists should be paginated rather than returned whole.
Abstract types listing fields that implementers must have, like interface Node { id: ID! }. Query the shared fields directly and use inline fragments for type-specific ones; the server needs a type resolver.
A type that is one of several object types with no shared fields required, e.g. union SearchResult = User | Post. Clients select through inline fragments and use __typename to branch.
The fields on Query, Mutation and Subscription — the entry points into the graph. Keep them few and well named; everything else should be reachable by following relationships.
Before running anything the server checks the document against the schema: fields must exist, arguments must match types, fragments must be used and spread on compatible types, and variables must be declared. Invalid documents fail as a whole with errors, and production servers often add extra rules for depth and cost limits.
Execution walks the validated document from the root type, calls each field's resolver with its parent value, and assembles the results into the response. Errors are caught per field, recorded in errors with a path, and the field becomes null, bubbling up to the nearest nullable parent.
Functions with the signature (parent, args, context, info) that return a field's value. Put per-request data like the user and DataLoaders in context, and batch database lookups to avoid N+1 queries.
A resolver may simply return a value, such as a property already on the parent object. Default resolvers do this for you when a field name matches a property, which is why most leaf fields need no code.
Resolvers that return a promise (or the language's equivalent) are awaited by the executor, and independent sibling fields are resolved concurrently. This is where database and HTTP calls live.
Converting resolver results into the declared scalar type on output, and literal or variable values into internal values on input. An Int field returning "5" is coerced; returning 5.5 produces a field error.
The response is a map with data and, when something failed, errors (each with message, locations and path) and optional extensions. Partial data with errors is a normal, valid outcome.
GraphQL does not define a transport, so serving it means picking one: plain HTTP for queries and mutations, and a streaming protocol for subscriptions. Usually a single endpoint such as /graphql handles everything, sitting behind the same auth and gateways as the rest of your stack.
The default transport: a POST with a JSON body of query, variables and operationName, or a GET with those as URL parameters for cacheable queries. The working group is standardising the details, including media types and status codes.
The draft spec defines application/graphql-response+json, when to return non-200 status codes, and that mutations must not go over GET. graphql-http ships an audit suite to check a server against it.
A single POST endpoint defeats HTTP caching, so clients cache normalised objects by __typename and id. For CDN caching, send queries over GET or use persisted queries with stable hashes.
Two different ideas: batching several operations into one HTTP request (an array body, supported by some servers), and batching data loads inside one request with DataLoader. The second matters far more for performance.
Authenticate in HTTP middleware and put the user on context; enforce permissions in the business layer that resolvers call, not in the schema shape. The same rules apply over WebSockets and SSE, where the token arrives at connection time.
The common transport for subscriptions: one persistent socket multiplexes many operations. Two protocols exist with confusingly similar names — the legacy subscriptions-transport-ws and its replacement graphql-ws — and client and server must agree on which one.
The graphql-transport-ws subprotocol: the client sends connection_init (often carrying an auth token), waits for connection_ack, then sends subscribe messages and receives next, error and complete.
Pushing updates as they happen: chat, notifications, live dashboards. Budget for many open connections, sticky load balancing or a shared pub/sub, and reconnect logic on the client.
Server-Sent Events stream results over ordinary HTTP, so they pass through proxies and HTTP/2 multiplexing without a protocol upgrade. The graphql-sse protocol has a simple distinct-connection mode and a single-connection mode with reservation tokens; auth uses normal HTTP headers.
Never return unbounded lists. Offset arguments (limit, offset) are easy but drift as data changes; cursor pagination with first/after and a pageInfo { hasNextPage endCursor } object is the stable choice, and the Relay connection spec is the convention most tools understand.
Every major language has a GraphQL server library, most built on the reference implementation's design. Pick by ecosystem and by schema style: SDL-first (write the schema, attach resolvers) or code-first (types generated from your classes or structs).
The JavaScript reference implementation maintained by the GraphQL Foundation. It provides parsing, validation and execution; nearly every Node server, including Apollo and Yoga, runs on top of it.
A minimal, spec-compliant GraphQL over HTTP server and client with adapters for Node, Express, Fastify and fetch-style runtimes. Good when you want no framework, and its audit tool tests other servers too.
The Guild's batteries-included server built on the Fetch API, so it runs on Node, Bun, Deno and edge workers. Uses Envelop plugins and supports subscriptions over SSE out of the box.
A widely used Node server with an embedded sandbox, plugins, caching hints and first-class Apollo Federation support for composing many subgraphs into one supergraph.
A GraphQL adapter for Fastify focused on speed, with JIT-compiled queries, built-in loaders for N+1 batching, subscriptions and federation support.
A Go port of GraphQL.js where you build the schema in code. Many Go teams prefer gqlgen, which generates type-safe resolvers from SDL.
The core Java engine with DataLoader support and instrumentation hooks. Spring for GraphQL builds on it, so most Spring Boot projects use it indirectly.
A code-first Python library where types are classes and resolvers are resolve_<field> methods, with integrations for Django and SQLAlchemy. Strawberry is a newer type-hint-based alternative.
You can call GraphQL with plain fetch, but a client library adds a normalised cache, request deduplication, optimistic updates and subscriptions. Pair it with GraphQL Code Generator or the library's compiler to get typed results.
Meta's React client with an ahead-of-time compiler, colocated fragments per component and strict data masking. Very fast and scalable, but it expects a server that follows its node and connection conventions.
The most widely used client: useQuery, useMutation and a normalised InMemoryCache keyed by __typename and id, with type policies for pagination and local state. Works with React and, through community bindings, other frameworks.
A small, extensible client built around exchanges (middleware). Its default cache is document-based; add Graphcache for normalised caching. Bindings exist for React, Vue, Svelte and Solid.