GraphQL
GraphQL from the schema up — the type system, queries, mutations and subscriptions, building a server with resolvers and DataLoader, schema design and pagination, Apollo Client and other clients, security and performance, and federation and production. API-style theory stays in api-design and the language in javascript. Fifty-nine lessons.
What GraphQL is and why it existsGraphQL is a typed query language for APIs where the client names the fields it wants, from the problem it solved at Facebook to a first run in graphql-js.GraphQL vs RESTCompare GraphQL and REST on fetching, versioning, caching, errors and tooling, and learn when each one is the better fit rather than picking a side.Your first query in GraphiQLStart a GraphQL Yoga server, open its built-in GraphiQL explorer, read the docs panel, write a query with autocomplete, and use variables and headers.GraphQL over HTTPSee 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.The GraphQL ecosystemA map of the GraphQL tool landscape, with servers, clients, explorers, code generators, gateways and where each fits, so the rest of the roadmap has a frame.Schema definition languageRead and write GraphQL's schema definition language: type declarations, descriptions, the Query root type, extend, and what the parser can and cannot catch.Scalar types and custom scalarsThe five built-in GraphQL scalars, how input and output coercion works, and how to write a DateTime custom scalar with serialize, parseValue and parseLiteral.Object types and fieldsObject types and their fields are the core of a GraphQL schema, including nesting, fields with arguments, computed fields, and how a field maps to a resolver.Non-null and listsHow the ! and [] modifiers combine into four list types, how null propagates up to the nearest nullable parent, and how to choose between nullable and required.EnumsDefine a fixed set of allowed values with a GraphQL enum, see how names differ from internal values, how enums are validated, and how to deprecate a value.InterfacesUse an interface when several object types share fields, query it with inline fragments and __typename, and how the server resolves the concrete type.UnionsModel a field that can return one of several unrelated object types with a GraphQL union, query it with inline fragments, and use unions for result types.Input typesUse input object types to group arguments into one structured value, with defaults, nested inputs, required fields, and the oneOf directive for either-or input.Fields and selection setsLearn the anatomy of a GraphQL query, from the operation to nested selection sets, how fields map to the response, and the rules the validator enforces.ArgumentsPass arguments to GraphQL fields to choose, filter and limit data, with defaults, required arguments, enum and ID arguments, and how the validator checks them.AliasesRename fields in a GraphQL response and query the same field twice with different arguments using aliases, plus how they resolve field conflicts in validation.FragmentsReuse field selections with named fragments, pick type-specific fields with inline fragments, and see how the validator checks type conditions and cycles.Variables and operation namesSend values separately from the query text with typed variables, set defaults, name operations, and pick one operation from a document with several.DirectivesUse @include and @skip to shape queries, @deprecated to retire fields, and how custom directives are declared but not run by default.IntrospectionQuery a GraphQL schema with __schema and __type, understand how GraphiQL and code generators use it, and why production servers often restrict it.MutationsWrite data with the Mutation root type, send variables, return the changed object, and see why mutation fields run serially while queries run in parallel.Designing mutation inputs and payloadsOne input object and one payload type per mutation, expected failures as userErrors, and the difference between an omitted field and an explicit null.SubscriptionsA subscription streams results as events happen. Define the root, return an async iterator, publish from a mutation, and filter per client.Subscriptions over WebSockets and SSECarry subscriptions over server-sent events with no setup, or WebSockets with graphql-ws, and choose by proxies, auth and connection limits.Defer and streamSend a response in pieces: @defer delivers slow fields after the rest, @stream sends list items as they are ready, over a multipart HTTP response.ResolversA resolver produces one field's value. See how execution walks the query, why default resolvers cover most fields, and how Query.post leads to Post.author.Context and resolver argumentsEvery resolver receives parent, args, context and info. Build context once per request for the database and current user, and learn what info is for.Schema-first and code-firstAuthor one schema two ways: write SDL and attach resolvers, or build types in code with graphql-js. Compare the output and when to pick each.A server with GraphQL YogaStand up a GraphQL server with graphql-yoga on Node: schema, resolvers, context, built-in GraphiQL, and a Fetch handler you can test offline.Connecting a databasePut SQLite behind resolvers: open the handle once, pass it via context, use parameterised queries, map columns to fields, and use transactions.The N+1 problemPer-field resolvers turn one list query into 1 + N database calls. Count the queries, see why GraphQL invites it, and what a fix must do.DataLoader and batchingFix N+1 with DataLoader: batch keys from one tick into one query, cache per request, and build loaders in context. 11 queries become 2.Errors and partial responsesA response can carry data and errors together. See how a failing field nulls itself or its parent, what errors holds, and why 200 is not success.Schema design principlesDesign the schema around what clients need, not your tables: model the domain, name actions for intent, be specific, and keep one graph.Naming conventionsNaming habits for a readable schema: PascalCase types, camelCase fields, SCREAMING_SNAKE_CASE enum values, verb-first mutations, Input and Payload suffixes.Nullability in practiceDecide where the exclamation mark goes: why fields are nullable by default, how one failing non-null field blanks a response, what to promise.Pagination: offset and cursorPage a list with limit and offset or an opaque cursor. See offset repeat items, measure deep-page cost, and build a keyset cursor.Relay connectionsThe Relay connection pattern: a connection type with edges, a cursor per edge and pageInfo, with a working Yoga resolver over ten posts.Global object identificationGive every object a globally unique ID and a Node interface with node(id) so clients can refetch anything by ID. Built and run on Yoga.Evolving a schema without versionsChange a schema without a v2: add fields freely, deprecate before removing, tell breaking changes from safe ones, and check usage first.Calling GraphQL with fetchA GraphQL request is one HTTP POST with a JSON body. Send queries and variables with plain fetch, read the errors array, and see what a client adds.Apollo Client basicsSet up ApolloClient with an HttpLink and an InMemoryCache, read data with useQuery, and see what the client adds beyond a bare fetch call.The Apollo cacheHow InMemoryCache normalizes responses into entities keyed by typename and id, why one edit shows up everywhere, and how keyFields and eviction work.Mutations and optimistic UI on the clientRun mutations with Apollo Client, keep the cache current with refetchQueries or update, and show results early with optimisticResponse.urql and RelayTwo alternatives to Apollo Client: urql with its small core and document cache, and Relay with its compiler and fragment colocation for large apps.Code generation and typed operationsGenerate TypeScript types and typed document nodes from your schema and operations with GraphQL Code Generator's client preset.Authentication and authorizationAuthenticate once per request in the context function, then authorize where data is resolved, with stable error codes and no top-level-only checks.Query depth and complexity limitsOne small query can demand millions of nodes in a cyclic schema. Cap depth and estimated cost in GraphQL Yoga with GraphQL Armor, and learn what limits miss.Rate limiting and cost analysisRequest counts are the wrong unit for GraphQL. Limit per field, budget by query cost, choose the right key, and enforce limits in front of the server.Persisted queriesReplace query text on the wire with a hash. Allowlists block arbitrary operations, automatic persisted queries save bandwidth, and both enable GET caching.Disabling introspection and hardeningTurning introspection off hides the schema map but does not secure an API. See what still leaks, then cover GraphiQL, error masking and batching.Caching GraphQLWhy one POST URL defeats HTTP caching, and the layers that work instead: client cache, DataLoader, server response cache with invalidation, and CDN.Schema stitching and federationTwo ways to present several GraphQL services as one schema: stitching merges them in a gateway, federation has each service declare how types join.Apollo Federation basicsBuild two subgraphs sharing a Product entity with @key, resolve it through _entities, and compose them into a supergraph with Rover.The router and the supergraphThe router is the endpoint clients call. It loads the supergraph, plans each query across subgraphs, fetches in parallel or sequence, and merges results.Testing a GraphQL APITest a schema by executing real queries against it, directly with graphql() and through yoga.fetch, including errors, auth and schema snapshots.Observability and tracingOne URL and mostly 200 responses hide GraphQL problems. Add per-operation metrics, OpenTelemetry resolver traces, and error tracking that reads errors.Schema registry and CI checksGate every schema change in CI. Diff against the published schema with GraphQL Inspector, fail on breaking changes, and see what a registry adds.Deploying GraphQLA GraphQL server is a fetch handler that runs on Node or the edge. Configure by environment, add health checks, and roll out schema changes safely.
Getting started
- What GraphQL is and why it existsGraphQL is a typed query language for APIs where the client names the fields it wants, from the problem it solved at Facebook to a first run in graphql-js.
- GraphQL vs RESTCompare GraphQL and REST on fetching, versioning, caching, errors and tooling, and learn when each one is the better fit rather than picking a side.
- Your first query in GraphiQLStart a GraphQL Yoga server, open its built-in GraphiQL explorer, read the docs panel, write a query with autocomplete, and use variables and headers.
- GraphQL over HTTPSee 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.
- The GraphQL ecosystemA map of the GraphQL tool landscape, with servers, clients, explorers, code generators, gateways and where each fits, so the rest of the roadmap has a frame.
The schema and type system
- Schema definition languageRead and write GraphQL's schema definition language: type declarations, descriptions, the Query root type, extend, and what the parser can and cannot catch.
- Scalar types and custom scalarsThe five built-in GraphQL scalars, how input and output coercion works, and how to write a DateTime custom scalar with serialize, parseValue and parseLiteral.
- Object types and fieldsObject types and their fields are the core of a GraphQL schema, including nesting, fields with arguments, computed fields, and how a field maps to a resolver.
- Non-null and listsHow the ! and [] modifiers combine into four list types, how null propagates up to the nearest nullable parent, and how to choose between nullable and required.
- EnumsDefine a fixed set of allowed values with a GraphQL enum, see how names differ from internal values, how enums are validated, and how to deprecate a value.
- InterfacesUse an interface when several object types share fields, query it with inline fragments and __typename, and how the server resolves the concrete type.
- UnionsModel a field that can return one of several unrelated object types with a GraphQL union, query it with inline fragments, and use unions for result types.
- Input typesUse input object types to group arguments into one structured value, with defaults, nested inputs, required fields, and the oneOf directive for either-or input.
Querying
- Fields and selection setsLearn the anatomy of a GraphQL query, from the operation to nested selection sets, how fields map to the response, and the rules the validator enforces.
- ArgumentsPass arguments to GraphQL fields to choose, filter and limit data, with defaults, required arguments, enum and ID arguments, and how the validator checks them.
- AliasesRename fields in a GraphQL response and query the same field twice with different arguments using aliases, plus how they resolve field conflicts in validation.
- FragmentsReuse field selections with named fragments, pick type-specific fields with inline fragments, and see how the validator checks type conditions and cycles.
- Variables and operation namesSend values separately from the query text with typed variables, set defaults, name operations, and pick one operation from a document with several.
- DirectivesUse @include and @skip to shape queries, @deprecated to retire fields, and how custom directives are declared but not run by default.
- IntrospectionQuery a GraphQL schema with __schema and __type, understand how GraphiQL and code generators use it, and why production servers often restrict it.
Mutations and subscriptions
- MutationsWrite data with the Mutation root type, send variables, return the changed object, and see why mutation fields run serially while queries run in parallel.
- Designing mutation inputs and payloadsOne input object and one payload type per mutation, expected failures as userErrors, and the difference between an omitted field and an explicit null.
- SubscriptionsA subscription streams results as events happen. Define the root, return an async iterator, publish from a mutation, and filter per client.
- Subscriptions over WebSockets and SSECarry subscriptions over server-sent events with no setup, or WebSockets with graphql-ws, and choose by proxies, auth and connection limits.
- Defer and streamSend a response in pieces: @defer delivers slow fields after the rest, @stream sends list items as they are ready, over a multipart HTTP response.
Building a server
- ResolversA resolver produces one field's value. See how execution walks the query, why default resolvers cover most fields, and how Query.post leads to Post.author.
- Context and resolver argumentsEvery resolver receives parent, args, context and info. Build context once per request for the database and current user, and learn what info is for.
- Schema-first and code-firstAuthor one schema two ways: write SDL and attach resolvers, or build types in code with graphql-js. Compare the output and when to pick each.
- A server with GraphQL YogaStand up a GraphQL server with graphql-yoga on Node: schema, resolvers, context, built-in GraphiQL, and a Fetch handler you can test offline.
- Connecting a databasePut SQLite behind resolvers: open the handle once, pass it via context, use parameterised queries, map columns to fields, and use transactions.
- The N+1 problemPer-field resolvers turn one list query into 1 + N database calls. Count the queries, see why GraphQL invites it, and what a fix must do.
- DataLoader and batchingFix N+1 with DataLoader: batch keys from one tick into one query, cache per request, and build loaders in context. 11 queries become 2.
- Errors and partial responsesA response can carry data and errors together. See how a failing field nulls itself or its parent, what errors holds, and why 200 is not success.
Schema design
- Schema design principlesDesign the schema around what clients need, not your tables: model the domain, name actions for intent, be specific, and keep one graph.
- Naming conventionsNaming habits for a readable schema: PascalCase types, camelCase fields, SCREAMING_SNAKE_CASE enum values, verb-first mutations, Input and Payload suffixes.
- Nullability in practiceDecide where the exclamation mark goes: why fields are nullable by default, how one failing non-null field blanks a response, what to promise.
- Pagination: offset and cursorPage a list with limit and offset or an opaque cursor. See offset repeat items, measure deep-page cost, and build a keyset cursor.
- Relay connectionsThe Relay connection pattern: a connection type with edges, a cursor per edge and pageInfo, with a working Yoga resolver over ten posts.
- Global object identificationGive every object a globally unique ID and a Node interface with node(id) so clients can refetch anything by ID. Built and run on Yoga.
- Evolving a schema without versionsChange a schema without a v2: add fields freely, deprecate before removing, tell breaking changes from safe ones, and check usage first.
Clients
- Calling GraphQL with fetchA GraphQL request is one HTTP POST with a JSON body. Send queries and variables with plain fetch, read the errors array, and see what a client adds.
- Apollo Client basicsSet up ApolloClient with an HttpLink and an InMemoryCache, read data with useQuery, and see what the client adds beyond a bare fetch call.
- The Apollo cacheHow InMemoryCache normalizes responses into entities keyed by typename and id, why one edit shows up everywhere, and how keyFields and eviction work.
- Mutations and optimistic UI on the clientRun mutations with Apollo Client, keep the cache current with refetchQueries or update, and show results early with optimisticResponse.
- urql and RelayTwo alternatives to Apollo Client: urql with its small core and document cache, and Relay with its compiler and fragment colocation for large apps.
- Code generation and typed operationsGenerate TypeScript types and typed document nodes from your schema and operations with GraphQL Code Generator's client preset.
Security and performance
- Authentication and authorizationAuthenticate once per request in the context function, then authorize where data is resolved, with stable error codes and no top-level-only checks.
- Query depth and complexity limitsOne small query can demand millions of nodes in a cyclic schema. Cap depth and estimated cost in GraphQL Yoga with GraphQL Armor, and learn what limits miss.
- Rate limiting and cost analysisRequest counts are the wrong unit for GraphQL. Limit per field, budget by query cost, choose the right key, and enforce limits in front of the server.
- Persisted queriesReplace query text on the wire with a hash. Allowlists block arbitrary operations, automatic persisted queries save bandwidth, and both enable GET caching.
- Disabling introspection and hardeningTurning introspection off hides the schema map but does not secure an API. See what still leaks, then cover GraphiQL, error masking and batching.
- Caching GraphQLWhy one POST URL defeats HTTP caching, and the layers that work instead: client cache, DataLoader, server response cache with invalidation, and CDN.
Federation and production
- Schema stitching and federationTwo ways to present several GraphQL services as one schema: stitching merges them in a gateway, federation has each service declare how types join.
- Apollo Federation basicsBuild two subgraphs sharing a Product entity with @key, resolve it through _entities, and compose them into a supergraph with Rover.
- The router and the supergraphThe router is the endpoint clients call. It loads the supergraph, plans each query across subgraphs, fetches in parallel or sequence, and merges results.
- Testing a GraphQL APITest a schema by executing real queries against it, directly with graphql() and through yoga.fetch, including errors, auth and schema snapshots.
- Observability and tracingOne URL and mostly 200 responses hide GraphQL problems. Add per-operation metrics, OpenTelemetry resolver traces, and error tracking that reads errors.
- Schema registry and CI checksGate every schema change in CI. Diff against the published schema with GraphQL Inspector, fail on breaking changes, and see what a registry adds.
- Deploying GraphQLA GraphQL server is a fetch handler that runs on Node or the edge. Configure by environment, add health checks, and roll out schema changes safely.