GraphQL Reference & Cheatsheet
Searchable GraphQL syntax reference — queries, mutations, subscriptions, fragments, directives, scalar types, and full real-world examples. Copy-paste ready.
Showing 17 of 17 syntax patterns
Query
QueryBasic query to fetch data from a GraphQL API.
{
user {
id
name
email
}
}Named Query
QueryNamed queries improve debugging and help identify operations in logs.
query GetUser {
user {
id
name
email
}
}Query with Variables
QueryUse variables to pass dynamic values without string interpolation.
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
# Variables:
# { "id": "123" }Mutation
MutationMutations are used to create, update, or delete data.
mutation {
createUser(name: "Alice", email: "alice@example.com") {
id
name
email
}
}Mutation with Variables
MutationBest practice: always use variables for mutation inputs.
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
}
}
# Variables:
# { "input": { "name": "Alice", "email": "alice@example.com" } }Subscription
SubscriptionSubscriptions allow real-time updates over a persistent connection (WebSocket).
subscription OnNewMessage($roomId: ID!) {
messageAdded(roomId: $roomId) {
id
text
author {
name
}
}
}Fragment
FragmentFragments reuse field selections across multiple queries.
fragment UserFields on User {
id
name
email
avatar
}
query {
me {
...UserFields
}
admin {
...UserFields
role
}
}Inline Fragment
FragmentInline fragments select fields on specific concrete types in a union or interface.
query GetSearchResults($term: String!) {
search(term: $term) {
... on User {
name
email
}
... on Post {
title
publishedAt
}
... on Product {
name
price
}
}
}Schema Definition
SchemaThe root schema definition connecting query, mutation, and subscription types.
schema {
query: Query
mutation: Mutation
subscription: Subscription
}Type Definition
SchemaObject types define the shape of data returned by the API.
type User {
id: ID!
name: String!
email: String!
age: Int
posts: [Post!]!
createdAt: String!
}Input Type
SchemaInput types define the shape of arguments for mutations and queries.
input CreateUserInput {
name: String!
email: String!
age: Int
role: UserRole = USER
}Enum Type
SchemaEnums restrict a field to a specific set of allowed values.
enum UserRole {
ADMIN
EDITOR
USER
GUEST
}Interface
SchemaInterfaces define a set of fields that implementing types must include.
interface Node {
id: ID!
}
interface Timestamped {
createdAt: String!
updatedAt: String!
}
type User implements Node & Timestamped {
id: ID!
name: String!
createdAt: String!
updatedAt: String!
}Union
SchemaUnions allow a field to return one of several object types.
union SearchResult = User | Post | Product
type Query {
search(term: String!): [SearchResult!]!
}Field Arguments
QueryFields can accept arguments to filter, sort, or paginate results.
query {
users(
first: 10
after: "cursor123"
orderBy: { field: CREATED_AT, direction: DESC }
filter: { role: ADMIN }
) {
edges {
node {
id
name
}
}
pageInfo {
hasNextPage
endCursor
}
}
}Aliases
QueryAliases rename fields in the response, useful when querying the same field twice.
query {
activeUser: user(id: "1") {
name
status
}
suspendedUser: user(id: "2") {
name
status
}
}Operation Name
QueryOperation names make operations identifiable in logs and Apollo DevTools.
query FetchDashboard {
currentUser {
id
name
notifications(unread: true) {
count
}
}
recentPosts(limit: 5) {
id
title
}
}What is GraphQL?
GraphQL is a query language for APIs and a server-side runtime for executing those queries. Originally developed by Facebook in 2012 and open-sourced in 2015, it provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need, makes it easier to evolve APIs over time, and enables powerful developer tooling.
Unlike REST APIs where multiple endpoints return fixed data structures, a GraphQL API exposes a single endpoint and lets the client specify the exact shape of the data it needs. This eliminates over-fetching (getting more data than needed) and under-fetching (requiring multiple requests to get all the data needed).
GraphQL vs REST
REST and GraphQL are both valid approaches to API design. REST uses multiple endpoints — one per resource — and returns a fixed shape of data. GraphQL uses a single endpoint and lets clients request exactly the fields they need in a single round-trip.
GraphQL shines when: you have multiple clients (web, mobile, third-party) with different data needs; you need to aggregate data from multiple sources; your API evolves frequently; or you want strong typing and introspection built in. REST shines for simple CRUD services, file uploads, caching via HTTP, or when you want standard HTTP semantics (status codes, methods).
Common GraphQL Patterns
Pagination: Use cursor-based pagination (the Relay connection spec) with edges, node, and pageInfo for stable pagination across large datasets.
Error Handling: GraphQL returns HTTP 200 even for business logic errors. Errors appear in the errors array alongside partial data in the data field.
N+1 Problem: Avoid the N+1 query problem by using DataLoader (batching and caching) to batch individual database lookups into a single query per request cycle.
Federation: Split a large GraphQL API across multiple independent microservices using Apollo Federation directives like @key, @external, and @requires.
FAQ
What is the difference between a query and a mutation in GraphQL?
Queries are read-only operations that fetch data without side effects. Mutations are write operations that create, update, or delete data and may also return the modified data. By convention, GraphQL clients run queries in parallel but execute mutations sequentially.
What is a GraphQL fragment?
A fragment is a reusable unit of field selections. You define it once with a name and the type it applies to, then spread it (using ...FragmentName) across multiple queries or mutations. This reduces duplication and keeps your queries DRY.
What is the difference between @include and @skip directives?
@include(if: Boolean) conditionally includes a field when the argument is true. @skip(if: Boolean) conditionally skips (excludes) a field when the argument is true. They are logical inverses of each other. Both accept a Boolean variable or literal.
What are GraphQL subscriptions used for?
Subscriptions enable real-time communication. The client subscribes to an event on the server, and the server pushes updates over a persistent connection (usually WebSocket) whenever that event occurs. Common use cases include live chat messages, notification feeds, stock price updates, and collaborative editing.
What is the ID scalar type in GraphQL?
The ID scalar represents a unique identifier and is serialized as a String. It is used to uniquely identify objects and is intended for use with caching and refetching. Values can be numeric strings or UUIDs — the important thing is they are unique within their type.