GraphQL
Updated: May 22, 2026Categories: Query, Backend
Printed from:
GraphQL Cheatsheet: Mastering Flexible and Efficient Data Fetching
1. Basic Concepts and Setup
What is GraphQL?
- A query language and runtime for APIs
- Single endpoint approach (HTTP POST, or GET for queries)
- Client-specified queries
- Strongly typed schema
- Governed by the GraphQL Specification (October 2021 edition, with ongoing working drafts)
Core Components
- Schema: Defines the shape of your data
- Query: Fetching data
- Mutation: Modifying data
- Subscription: Real-time updates
GraphQL over HTTP
- Standardized
application/graphql-response+jsonmedia type for responses - Recommended single endpoint (commonly
/graphql) - Use POST for mutations; GET allowed for queries (helps with HTTP caching)
2. Schema Definition Language (SDL) Basics
Basic SDL Syntax
graphql
1234567type User {
id: ID!
name: String
email: String!
age: Int
}
Key SDL Syntax Elements
!: Required field (non-nullable)[Type!]!: Non-null list of non-null itemsID: Unique identifier typeString,Int,Boolean,Float: Scalar types"""Description""": Markdown-capable schema descriptions
3. Scalar Types and Custom Types
Built-in Scalar Types
graphql
123456scalar String # UTF-8 text
scalar Int # 32-bit signed integer
scalar Float # Double-precision floating-point
scalar Boolean # true/false
scalar ID # Unique identifier (serialized as String)
Custom Scalar Types
graphql
123456scalar DateTime
scalar EmailAddress
scalar URL
scalar JSON
scalar BigInt
- Reusable, spec-compliant implementations are available via the
graphql-scalarslibrary.
4. Object Types, Interfaces, and Unions
Object Type Definition
graphql
123456789101112type Person {
name: String!
age: Int
address: Address
}
type Address {
street: String!
city: String!
country: String!
}
Interface Definition
graphql
1234567891011121314151617interface Character {
id: ID!
name: String!
}
type Hero implements Character {
id: ID!
name: String!
superpower: String
}
type Villain implements Character {
id: ID!
name: String!
evilPlan: String
}
Interfaces Implementing Interfaces
graphql
123456789interface Node {
id: ID!
}
interface Character implements Node {
id: ID!
name: String!
}
Union Types
graphql
12union SearchResult = User | Post | Comment
Input Objects with Default Values
graphql
12345input UserFilter {
active: Boolean = true
role: Role = MEMBER
}
Input Object @oneOf (polymorphic input)
graphql
123456input UserBy @oneOf {
id: ID
email: String
username: String
}
@oneOfenforces that exactly one field is provided — useful for "find by" inputs.
5. Query Operations and Syntax
Basic Query
graphql
1234567query {
user(id: "123") {
name
email
}
}
Nested Queries
graphql
12345678910111213query {
user(id: "123") {
name
posts {
title
comments {
text
author
}
}
}
}
Named Operations and Aliases
graphql
12345query GetTwoUsers {
primary: user(id: "1") { name }
secondary: user(id: "2") { name }
}
6. Mutations for Data Modification
Create Mutation
graphql
1234567mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
}
}
Update Mutation
graphql
1234567mutation UpdateUser($id: ID!, $input: UpdateUserInput!) {
updateUser(id: $id, input: $input) {
id
name
}
}
- Mutations execute serially; queries execute in parallel.
- Prefer a single
inputargument per mutation for forward compatibility.
7. Subscriptions for Real-Time Data
Subscription Example
graphql
12345678910subscription OnNewMessage($channelId: ID!) {
newMessage(channelId: $channelId) {
id
text
sender {
name
}
}
}
Transports
- graphql-ws (WebSocket sub-protocol
graphql-transport-ws) — current standard - graphql-sse — Server-Sent Events transport for unidirectional streams
- The legacy
subscriptions-transport-wslibrary is unmaintained and should be replaced.
8. Arguments and Variables
Query with Arguments
graphql
123456789101112131415query GetUsers($limit: Int = 10, $filter: UserFilter) {
users(limit: $limit, filter: $filter) {
name
email
}
}
# Variables
{
"limit": 10,
"filter": {
"active": true
}
}
9. Fragments and Inline Fragments
Fragment Definition
graphql
123456789101112fragment UserDetails on User {
id
name
email
}
query {
users {
...UserDetails
}
}
Inline Fragment
graphql
12345678query {
search(query: "example") {
__typename
... on User { name }
... on Post { title }
}
}
Fragment Arguments (draft spec, supported by some tooling)
graphql
1234fragment Avatar($size: Int = 64) on User {
avatarUrl(size: $size)
}
10. Directives
Built-in Directives
graphql
12345678910111213141516query ($showEmail: Boolean!) {
user {
name
email @include(if: $showEmail)
phone @skip(if: $showEmail)
}
}
type User {
legacyId: String @deprecated(reason: "Use id instead")
}
type Query {
feed: [Post!]! @specifiedBy(url: "https://example.com/feed-spec")
}
@defer and @stream (incremental delivery)
graphql
12345678query {
user(id: "1") {
name
...Slow @defer(label: "slow")
posts @stream(initialCount: 2)
}
}
- Requires a server and client supporting incremental delivery (e.g., GraphQL Yoga, Apollo Router, Relay, urql, graphql-js ≥ 17).
11. Introspection and Schema Exploration
Introspection Query
graphql
1234567{
__schema {
types { name kind }
queryType { name }
}
}
- Disable or restrict introspection in production for sensitive APIs.
12. Error Handling and Validation
Error Response
JSON
123456789101112131415{
"data": null,
"errors": [
{
"message": "User not found",
"locations": [{ "line": 2, "column": 3 }],
"path": ["user"],
"extensions": {
"code": "NOT_FOUND",
"http": { "status": 404 }
}
}
]
}
- Put machine-readable info under
extensions(e.g.,code,classification). - Consider an errors-as-data pattern with union result types for expected business errors:
graphql
12union CreateUserResult = User | EmailTakenError | ValidationError
13. Performance Optimization
N+1 Problem Solution (DataLoader)
JavaScript
1234567import DataLoader from 'dataloader';
const userLoader = new DataLoader(async (ids) => {
const users = await User.findByIds(ids);
return ids.map((id) => users.find((u) => u.id === id) ?? null);
});
Other Tactics
- Persisted queries / trusted documents — send query hashes instead of full strings; reduces payload and blocks arbitrary queries
- Automatic Persisted Queries (APQ) for HTTP GET caching
- Query complexity / depth limiting (e.g.,
graphql-validation-complexity,graphql-armor) - Response caching with Apollo Server / GraphQL Yoga response-cache plugins
@defer/@streamfor progressive rendering- Connection-style cursor pagination over offset pagination
14. Best Practices
- Design schemas around domain concepts, not database tables
- Use cursor-based (Relay-style) pagination with
Connection/Edgetypes - Implement field-level authorization (shield/rules engines, or directives)
- Evolve the schema — avoid breaking changes; mark removed fields with
@deprecated - Return meaningful errors with
extensions.code - Limit query depth, complexity, and rate
- Cache strategically (HTTP, response, and entity-level)
- Use trusted/persisted documents in production clients
- Prefer non-null where data is truly required, but be conservative — non-null propagation can null out parents
- Adopt the Relay Global Object Identification spec (
Nodeinterface, opaqueIDs)
15. Federation and Composition
- Apollo Federation v2 — subgraph composition with
@key,@shareable,@external,@requires,@provides,@interfaceObject - GraphQL Hive / Apollo Router / Cosmo Router — gateways for federated graphs
- Schema stitching is largely superseded by federation for new projects
graphql
12345type Product @key(fields: "id") {
id: ID!
name: String! @shareable
}
16. Ecosystem Tools
Clients
- Apollo Client
- Relay
- urql
- GraphQL Request
- TanStack Query + graphql-request
Servers
- Apollo Server 4
- GraphQL Yoga 5
- Mercurius (Fastify)
- Pothos (code-first schema builder, TypeScript)
- Nexus
- Strawberry (Python)
- Ariadne (Python)
- gqlgen (Go)
- async-graphql (Rust)
- Hot Chocolate (.NET)
- Hasura, PostGraphile, Grafbase (auto-generated from databases)
Gateways / Federation
- Apollo Router
- GraphQL Hive Gateway
- WunderGraph Cosmo Router
Development Tools
- GraphiQL (the official IDE; GraphQL Playground is deprecated)
- Apollo Sandbox / Apollo Explorer
- GraphQL Code Generator
- Rover CLI (Apollo)
- GraphQL Inspector (schema diffing / CI checks)
- GraphQL Armor (security middleware)
Additional Resources
- Official GraphQL Specification — https://spec.graphql.org
- GraphQL.org documentation and learning resources
- GraphQL over HTTP specification (working draft)
- GraphQL Foundation working groups and RFCs
Continue Learning
Discover more cheatsheets to boost your productivity