GraphQL Cheat Sheet
Quick reference for GraphQL schema design, query syntax, and client-side patterns. Covers SDL, operations, variables, directives, fragments, error handling, and Apollo Client.
Related: REST API Design | State Management
Schema Definition Language (SDL)
Scalar Types
| Type | Description |
|---|---|
Int | Signed 32-bit integer |
Float | Signed double-precision floating-point |
String | UTF-8 character sequence |
Boolean | true or false |
ID | Unique identifier (serialized as String) |
Int is 32-bit, so IDs, timestamps and money that exceed 2^31-1 need a custom scalar (BigInt, DateTime) or String. Every object also has the meta-field __typename.
Type Definitions
# Object type
type User {
id: ID!
name: String!
email: String!
age: Int
posts: [Post!]!
role: Role!
createdAt: DateTime!
}
# Enum
enum Role {
ADMIN
USER
MODERATOR
}
# Interface
interface Node {
id: ID!
}
interface Timestamped {
createdAt: DateTime!
updatedAt: DateTime!
}
# Implementing multiple interfaces
type Post implements Node & Timestamped {
id: ID!
title: String!
body: String!
author: User!
tags: [String!]!
status: PostStatus!
createdAt: DateTime!
updatedAt: DateTime!
}
# Union type
union SearchResult = User | Post | Comment
# Input type (for mutations)
input CreatePostInput {
title: String!
body: String!
tags: [String!] = []
status: PostStatus = DRAFT
}
# Custom scalar
scalar DateTime
scalar JSON
scalar URL @specifiedBy(url: "https://url.spec.whatwg.org/")
# Exactly one field must be set (OneOf input objects, GraphQL spec 2025)
input UserBy @oneOf {
id: ID
email: String
}
# Root operation types
type Query {
user(by: UserBy!): User
search(term: String!): [SearchResult!]!
}
type Mutation {
createPost(input: CreatePostInput!): CreatePostResult!
}
type Subscription {
messageCreated(roomId: ID!): Message!
}
# Extend a type defined elsewhere (modular schemas)
extend type Query {
me: User
}
"""
Descriptions are Markdown strings in triple quotes; they show up in GraphiQL and introspection.
"""
type Comment {
id: ID!
"Single-line description"
body: String!
}
Non-Null & Lists
| Syntax | Meaning |
|---|---|
String | Nullable string |
String! | Non-null string |
[String] | Nullable list of nullable strings |
[String!] | Nullable list of non-null strings |
[String!]! | Non-null list of non-null strings |
If a non-null field resolves to null (or throws), the null propagates up to the nearest nullable parent, so one failing field can null out a whole object or the entire data.
Queries
Basic Query
query GetUser {
user(id: "123") {
id
name
email
posts {
title
createdAt
}
}
}
With Variables
query GetUser($userId: ID!, $includeEmail: Boolean = false) {
user(id: $userId) {
id
name
email @include(if: $includeEmail)
posts(first: 10, orderBy: CREATED_AT_DESC) {
edges {
node {
title
}
}
}
}
}
Variables JSON:
{
"userId": "123",
"includeEmail": true
}
Sending a Query over HTTP
curl -X POST https://api.example.com/graphql \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer TOKEN' \
-d '{"query":"query GetUser($id: ID!) { user(id: $id) { name } }","variables":{"id":"123"},"operationName":"GetUser"}'
The body is always { query, variables?, operationName? }. Servers usually also accept GET /graphql?query=... for queries (never mutations). The GraphQL-over-HTTP spec recommends the application/graphql-response+json response type, with real HTTP status codes for request-level errors.
Introspection
{
__schema { types { name kind } }
}
{
__type(name: "User") { fields { name type { name kind ofType { name } } } }
}
Many servers disable introspection in production. Fetch the schema with tooling instead, e.g. npx get-graphql-schema https://api.example.com/graphql > schema.graphql or Rover (rover graph introspect URL).
Aliases
query ComparePosts {
firstPost: post(id: "1") {
title
viewCount
}
secondPost: post(id: "2") {
title
viewCount
}
}
Fragments
Named Fragments
fragment UserBasic on User {
id
name
email
avatar
}
fragment PostSummary on Post {
id
title
createdAt
author {
...UserBasic
}
}
query Dashboard {
me {
...UserBasic
role
}
recentPosts(limit: 10) {
...PostSummary
}
}
Inline Fragments (for Unions/Interfaces)
query Search($term: String!) {
search(term: $term) {
... on User {
id
name
email
}
... on Post {
id
title
author { name }
}
... on Comment {
id
body
post { title }
}
}
}
Mutations
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
title
status
author {
id
name
}
}
}
mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
updatePost(id: $id, input: $input) {
id
title
updatedAt
}
}
mutation DeletePost($id: ID!) {
deletePost(id: $id) {
success
message
}
}
Batch Mutations
Top-level mutation fields run in order, one after another (query fields may run in parallel).
mutation BatchOps {
updateUser(id: "1", input: { name: "New Name" }) {
id
name
}
publishPost(id: "42") {
id
status
}
}
Subscriptions
subscription OnNewMessage($roomId: ID!) {
messageCreated(roomId: $roomId) {
id
body
sender {
id
name
}
createdAt
}
}
Subscriptions usually run over WebSockets with the graphql-transport-ws protocol (the graphql-ws library). The older subscriptions-transport-ws package and its graphql-ws subprotocol name are unmaintained, and the names are confusingly swapped. Server-Sent Events (graphql-sse) is a simpler alternative over plain HTTP. A subscription operation must have exactly one top-level field.
Directives
Built-in Directives
| Directive | Usage |
|---|---|
@include(if: Boolean!) | Include field when condition is true |
@skip(if: Boolean!) | Skip field when condition is true |
@deprecated(reason: String) | Mark a field, enum value, argument or input field as deprecated in schema |
@specifiedBy(url: String!) | Link a custom scalar to its spec |
@oneOf | Input object where exactly one field must be provided (GraphQL spec 2025) |
@defer / @stream | Incremental delivery of slow fragments / list items. Still an RFC; supported by some servers and clients (Apollo, GraphQL Yoga) |
# Client-side
query GetUser($withPosts: Boolean!) {
user(id: "1") {
name
posts @include(if: $withPosts) {
title
}
}
}
Custom Directives (Schema)
# Define
directive @auth(requires: Role!) on FIELD_DEFINITION
directive @cacheControl(maxAge: Int!) on FIELD_DEFINITION
# Use
type Query {
publicPosts: [Post!]! @cacheControl(maxAge: 300)
adminDashboard: Dashboard! @auth(requires: ADMIN)
}
Pagination Patterns
Cursor-Based (Relay Style)
type Query {
posts(first: Int, after: String, last: Int, before: String): PostConnection!
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type PostEdge {
cursor: String!
node: Post!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
# Usage
query Posts($cursor: String) {
posts(first: 20, after: $cursor) {
edges {
cursor
node {
id
title
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
Offset-Based
type Query {
posts(limit: Int = 20, offset: Int = 0): PostList!
}
type PostList {
items: [Post!]!
total: Int!
}
TIP
Cursor-based pagination is more robust for real-time data. Offset-based is simpler but breaks when items are inserted/deleted during pagination.
Error Handling
Standard Error Format
{
"data": null,
"errors": [
{
"message": "User not found",
"locations": [{ "line": 2, "column": 3 }],
"path": ["user"],
"extensions": {
"code": "NOT_FOUND",
"statusCode": 404
}
}
]
}
Most servers return HTTP 200 even when errors is present, and a response can contain both data and errors (partial success). Always check errors, not just the status code.
extensions.code (Apollo Server) | Meaning |
|---|---|
GRAPHQL_PARSE_FAILED | Query is not valid syntax |
GRAPHQL_VALIDATION_FAILED | Query does not match the schema |
BAD_USER_INPUT | Invalid argument values |
UNAUTHENTICATED / FORBIDDEN | Auth errors (custom, by convention) |
PERSISTED_QUERY_NOT_FOUND | APQ hash not cached yet; resend with the full query |
INTERNAL_SERVER_ERROR | Unhandled resolver error |
Union-Based Errors (Recommended)
type Mutation {
createPost(input: CreatePostInput!): CreatePostResult!
}
union CreatePostResult = CreatePostSuccess | ValidationError | AuthError
type CreatePostSuccess {
post: Post!
}
type ValidationError {
field: String!
message: String!
}
type AuthError {
message: String!
}
mutation {
createPost(input: { title: "Hi", body: "..." }) {
__typename
... on CreatePostSuccess { post { id } }
... on ValidationError { field message }
... on AuthError { message }
}
}
Server-Side Essentials
Resolvers & DataLoader (Node.js)
import DataLoader from 'dataloader';
// One loader per request, so the cache never leaks between users
const createLoaders = () => ({
userById: new DataLoader(async (ids: readonly string[]) => {
const rows = await db.user.findMany({ where: { id: { in: [...ids] } } });
const byId = new Map(rows.map(u => [u.id, u]));
return ids.map(id => byId.get(id) ?? null); // same order and length as ids
}),
});
const resolvers = {
Query: {
post: (_parent, { id }, ctx) => ctx.db.post.findUnique({ where: { id } }),
},
Post: {
// (parent, args, context, info)
author: (post, _args, ctx) => ctx.loaders.userById.load(post.authorId),
},
SearchResult: {
__resolveType: (obj) => (obj.email ? 'User' : obj.title ? 'Post' : 'Comment'),
},
};
Protecting the Server
| Protection | How |
|---|---|
| Depth limit | graphql-depth-limit or server config (e.g. max 10) |
| Cost/complexity limit | graphql-query-complexity, Apollo/Yoga plugins |
| Persisted / trusted operations | Only allow pre-registered query hashes in production |
| Disable introspection in prod | Server option (introspection: false) |
| Timeouts & rate limits | Per operation, not just per HTTP request |
| Batching limits | Cap operations per batched HTTP request and aliases per query |
Persisted Queries
- APQ (Automatic Persisted Queries): client sends
extensions.persistedQuery.sha256Hash; on miss the server returnsPERSISTED_QUERY_NOT_FOUNDand the client retries with the full query. Saves bandwidth, enables GET + CDN caching. - Trusted documents: queries are extracted at build time and registered; the server rejects anything else. This is a security control, APQ is not.
Code Generation
npm i -D @graphql-codegen/cli @graphql-codegen/client-preset
npx graphql-codegen init # creates codegen.ts
npx graphql-codegen --watch # typed documents and hooks from schema + queries
Apollo Client Patterns
Examples use Apollo Client 4 (released September 2025). Main changes from v3: React hooks and ApolloProvider are imported from @apollo/client/react; the uri option on ApolloClient is gone, so you always pass a link; split is ApolloLink.split; ApolloError is replaced by error classes such as CombinedGraphQLErrors; useQuery no longer has onCompleted/onError. A codemod (npx @apollo/client-codemod-migrate-3-to-4) handles most of the import changes.
Setup
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';
import { ApolloProvider } from '@apollo/client/react';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { OperationTypeNode } from 'graphql';
import { createClient } from 'graphql-ws';
const httpLink = new HttpLink({ uri: '/graphql' });
const wsLink = new GraphQLWsLink(
createClient({ url: 'ws://localhost:4000/graphql' })
);
// Route subscriptions over WebSocket, everything else over HTTP
const splitLink = ApolloLink.split(
({ operationType }) => operationType === OperationTypeNode.SUBSCRIPTION,
wsLink,
httpLink
);
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
// <ApolloProvider client={client}><App /></ApolloProvider>
Apollo Client 3 equivalent (still common in existing code):
import { ApolloClient, InMemoryCache, HttpLink, split, useQuery } from '@apollo/client';
import { getMainDefinition } from '@apollo/client/utilities';
const splitLink = split(
({ query }) => {
const def = getMainDefinition(query);
return def.kind === 'OperationDefinition' && def.operation === 'subscription';
},
wsLink,
httpLink
);
useQuery
import { gql } from '@apollo/client';
import { useQuery, useMutation } from '@apollo/client/react'; // v3: from '@apollo/client'
const GET_POSTS = gql`
query GetPosts($limit: Int!) {
posts(limit: $limit) {
id
title
author { name }
}
}
`;
function PostList() {
const { data, loading, error, refetch } = useQuery(GET_POSTS, {
variables: { limit: 20 },
pollInterval: 30000, // refetch every 30s
fetchPolicy: 'cache-and-network',
});
if (loading) return <Spinner />;
if (error) return <Error message={error.message} />;
return data.posts.map(post => <PostCard key={post.id} post={post} />);
}
Other hooks: useLazyQuery (run on demand; in v4 await the returned execute function instead of using callbacks), useSuspenseQuery (React Suspense), useSubscription, useFragment (read a fragment from the cache).
// v4: inspect errors with the static .is() helpers
import { CombinedGraphQLErrors } from '@apollo/client';
if (CombinedGraphQLErrors.is(error)) {
error.errors.forEach(e => console.log(e.extensions?.code));
}
useMutation
const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
title
}
}
`;
function CreatePostForm() {
const [createPost, { loading }] = useMutation(CREATE_POST, {
// Update cache after mutation
update(cache, { data: { createPost } }) {
cache.modify({
fields: {
posts(existingPosts = []) {
const newRef = cache.writeFragment({
data: createPost,
fragment: gql`fragment NewPost on Post { id title }`,
});
return [...existingPosts, newRef];
},
},
});
},
onCompleted: () => toast.success('Post created'),
onError: (err) => toast.error(err.message),
});
const handleSubmit = (input) => {
createPost({ variables: { input } });
};
}
Fetch Policies
| Policy | Description |
|---|---|
cache-first | Read from cache, fetch only if missing (default) |
cache-and-network | Return cache immediately, then fetch and update |
network-only | Always fetch, then update cache |
cache-only | Only read from cache, never fetch |
no-cache | Always fetch, never read or write cache |
standby | Like cache-first but doesn't update automatically when the cache changes |
Cache Basics
const cache = new InMemoryCache({
typePolicies: {
Product: { keyFields: ['sku'] }, // when the id field isn't `id`/`_id`
Query: {
fields: {
posts: {
keyArgs: ['filter'], // separate cache entries per filter
merge(existing = [], incoming) { // append pages for infinite scroll
return [...existing, ...incoming];
},
},
},
},
},
});
client.refetchQueries({ include: ['GetPosts'] }); // refetch active queries by name
cache.evict({ id: cache.identify({ __typename: 'Post', id }) });
cache.gc();
Objects are normalized by __typename + id. A mutation that returns the changed object with its id updates the cache automatically; you only need update/refetchQueries when items are added or removed from lists.
WARNING
cache-first is the default. This is efficient but can show stale data. Use cache-and-network for data that changes frequently.
Schema Design Best Practices
| Practice | Why |
|---|---|
Use input types for mutations | Clear separation, reusable, versionable |
| Non-null where the value is guaranteed, nullable when needed | Fewer client null checks; but non-null fields propagate errors upward, so keep fields that call other services or can fail nullable (fields are nullable by default in GraphQL for this reason) |
| Use enums over strings | Type safety, autocomplete, validation |
| Cursor pagination over offset | Stable with real-time data |
| Union errors over thrown errors | Client handles all cases explicitly |
Consistent naming: createX, updateX, deleteX | Predictable API surface |
| Avoid deeply nested queries | N+1 risk, complexity budget |
| Version via new fields, not new endpoints | Additive schema evolution |
Mutation inputs: one input argument, return a payload type | Room to add fields later without breaking clients |
Global object IDs + node(id:) | Lets clients refetch any object; needed for Relay |
Test Yourself
-
What does
!mean after a type in GraphQL SDL? Non-null -- the field is guaranteed to return a value (never null). -
How do you request the same field with different arguments in one query? Use aliases:
firstPost: post(id: "1") { title } -
What directive conditionally includes a field based on a variable?
@include(if: $variable) -
What is the difference between
inputtypes and regular types?inputtypes are used for mutation arguments; regulartypedefinitions are for output/return types. -
How do you handle union types in a query? Use inline fragments:
... on User { name }and... on Post { title } -
What pagination style is recommended for real-time data? Cursor-based (Relay style) with
edges,node, andpageInfo. -
What Apollo Client fetch policy returns cached data immediately, then fetches and updates?
cache-and-network -
How do you mark a field as deprecated in the schema?
@deprecated(reason: "Use newField instead") -
What is the recommended approach for error handling in mutations? Union-based errors:
union CreatePostResult = CreatePostSuccess | ValidationError | AuthError -
How do you force the Apollo cache to update after a mutation? Use the
updatecallback onuseMutationto modify the cache directly withcache.modify.
Common Gotchas
- N+1 query problem. A naive resolver that fetches related data per-item creates N+1 database queries. Use DataLoader for batching.
- Over-fetching nested queries. Deeply nested queries can explode into huge responses. Implement query depth limiting and complexity analysis on the server.
cache-firstshows stale data. It is the Apollo Client default, but for frequently changing data, usecache-and-networkornetwork-only.- Confusing
nullfield vs missing field. A null field means the server returned null; a missing field means you did not request it. The!modifier prevents nulls at the schema level. - HTTP 200 does not mean success. Errors live in the
errorsarray, often next to partialdata. Clients and monitoring must check it. - Non-null fields amplify failures. One resolver error on a
!field nulls its parent, possibly all ofdata. - Forgetting
__typenameandidin selections. Apollo/Relay caches need them to normalize; withoutidan update creates a duplicate cache entry instead of merging. Intis only 32 bits. Large IDs or Unix timestamps in milliseconds overflow; useID,Stringor a custom scalar.- Aliases and batching bypass naive rate limits. One request can contain hundreds of aliased login attempts. Limit cost, not requests.
- Apollo Client 4 moved the React imports.
import { useQuery } from '@apollo/client'fails in v4; use@apollo/client/react.
One-Liner Summary
GraphQL lets clients request exactly the data they need in a single query -- master SDL types, fragments, variables, and cursor pagination to build flexible, efficient APIs.
Last updated: 2026-11-09