Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Practice and Review

GraphQL Cheat Sheet

A one-page GraphQL cheat sheet: query syntax, SDL types and modifiers, directives, operation patterns, error and pagination shapes, pitfalls and lesson links.

This is a quick reference for the whole tutorial: what to type, what it means, and where to read more. Everything here is read-only, because a real GraphQL server cannot run on this site. One small stand-in at the end lets you check the list notation you will use most.

Keep it open while you work, and follow the links when a line is not enough.

Query syntax

GRAPHQL
query GetBook($id: ID!, $withReviews: Boolean = false) {
  book(id: $id) {
    title
    author { name }
    cover: image(size: 200)
    reviews @include(if: $withReviews) { rating }
    ...BookBasics
  }
}

fragment BookBasics on Book {
  id
  pages
}
Piece Meaning Lesson
query / mutation / subscription Operation type; query can be left out for the shorthand { ... } First query
GetBook Operation name, useful for logs and tools Variables
$id: ID! Variable definition; = false is a default Variables
book(id: $id) Field with an argument Fields
cover: image(...) Alias: rename a field in the response Aliases
...BookBasics Fragment spread Fragments
... on Book { } Inline fragment with a type condition Interfaces and unions
__typename The object's concrete type name Interfaces and unions

Directives

Directive Where Effect
@include(if: Boolean!) Field, fragment Include only when true
@skip(if: Boolean!) Field, fragment Leave out when true
@deprecated(reason: String) Field, enum value, argument Marks something as going away
@specifiedBy(url: String!) Custom scalar Links to the scalar's specification
@oneOf Input object Exactly one field must be provided (newer addition; check your server supports it)

Servers can add their own directives (authorization, caching hints, federation's @key). Those are server-specific.

Schema (SDL)

GRAPHQL
"""A book in the catalog."""
type Book implements Node {
  id: ID!
  title: String!
  pages: Int
  tags: [String!]!
  author: Author!
  reviews(first: Int = 10, after: String): ReviewConnection!
  oldTitle: String @deprecated(reason: "Use title")
}

interface Node { id: ID! }
union SearchResult = Book | Author
enum Format { PAPERBACK EBOOK AUDIO }
scalar DateTime
input NewBook { title: String!  format: Format = PAPERBACK }

type Query { book(id: ID!): Book  search(text: String!): [SearchResult!]! }
type Mutation { addBook(input: NewBook!): AddBookPayload! }
type Subscription { bookAdded: Book! }
Kind Keyword Notes
Object type Output with fields; fields may take arguments
Interface interface Shared fields; types implements it
Union union A = B | C One of several types, no shared fields needed
Enum enum A fixed set of names
Input object input Used for arguments; no field arguments
Scalar scalar Leaf value: Int, Float, String, Boolean, ID or custom

Lessons: Types and scalars, Enums, interfaces, unions, Input types and introspection.

Nullability and lists

Type List can be null? Items can be null?
[T] yes yes
[T!] yes no
[T]! no yes
[T!]! no no

A plain T is nullable; T! is never null. A failing non-null field nulls its nearest nullable parent. See Lists and non-null types.

Operation patterns

Goal Pattern
Read one thing book(id: "7") { title }, usually nullable (not found is normal)
Read many Return [Item!]! or a connection
Change data One specific mutation per action, an input argument, a payload type back
Do several writes Several top-level mutation fields run in order; query fields may run in parallel
Listen for events subscription { bookAdded { id title } } over WebSocket or SSE
Avoid string building Always pass values as variables, never concatenate

See Mutations and subscriptions and Realtime and uploads.

Response shapes

Success, with a partial failure:

JSON
{
  "data": { "book": { "title": "Maps", "reviews": null } },
  "errors": [
    {
      "message": "Reviews service unavailable",
      "path": ["book", "reviews"],
      "extensions": { "code": "UPSTREAM_ERROR" }
    }
  ]
}

Relay-style connection:

GRAPHQL
{
  books(first: 2, after: "Y3Vyc29yOjI=") {
    edges { cursor node { id title } }
    pageInfo { hasNextPage endCursor }
  }
}

Expected failure modeled in the schema:

GRAPHQL
type AddBookPayload { book: Book  userErrors: [UserError!]! }
type UserError { field: [String!]  message: String! }

Lessons: Execution and errors, Pagination, Modeling errors.

Over HTTP

Terminal
curl -X POST https://api.example.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"query($id: ID!){ book(id:$id){ title } }","variables":{"id":"7"},"operationName":null}'

The body has query, optional variables and optional operationName. A GET request carries the same pieces in the URL (for example a persisted-query id). Details in GraphQL over HTTP.

Common pitfalls

Pitfall Better approach
A nullable-by-accident field that clients must always check Decide on ! deliberately (nullability)
Too many ! on fragile fields A single failure nulls a large part of the response
One resolver query per list item (N+1) Per-request DataLoader (N+1)
Sharing a DataLoader between requests Create loaders per request, in context
Authorization only in some resolvers Put it in the business layer (auth)
No depth or cost limits Add limits and timeouts (limits)
Generic updateThing(flags...) mutations Specific mutations with payloads (design)
Offset pagination on changing data Cursor connections (pagination)
Removing a field abruptly Deprecate, watch usage, then remove (evolution)
Assuming a 200 status means no errors Always check the errors array

A runnable check of the notation

This stand-in reads a type string such as [Int!]! and explains it in words, the way you read it aloud.

JS Stand-in: read a type out loud

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that "non-null" is added in front of whatever the rest says, so the outermost modifier is read first.

Every lesson at a glance

Chapter Lessons
Getting started What is GraphQL, GraphQL vs REST, First query
Writing queries Fields and arguments, Aliases and fragments, Variables and directives, Mutations and subscriptions
The schema Types and scalars, Lists and non-null, Enums, interfaces, unions, Input types and introspection
Resolvers and execution Resolvers, Execution and errors, N+1 and DataLoader
Schema design Best practices, Pagination, Modeling errors
Security and performance Auth, Query limits, Caching
Clients and transport Over HTTP, Clients and codegen, Realtime and uploads
Evolving and testing Testing, Evolution and federation
Projects Bookstore API, Todo mutations, Blog with DataLoader, Secured gateway
Practice Exercises, Interview questions

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. How do you read the type [Int]!?

    The ! after the brackets applies to the list; the items have no ! so they may be null.
  2. 2. Which directive leaves a field out when a Boolean variable is true?

    @skip(if: true) removes the field; @include(if: true) keeps it.
  3. 3. Which part of a response tells you a field failed even when the HTTP status is 200?

    Partial failures are reported in errors with a path, while data keeps whatever could be resolved.

Summary

  • Queries use operation, selection set, arguments, aliases, fragments and variables.
  • SDL has object, interface, union, enum, input and scalar types; ! and [ ] control nullability and lists.
  • Mutations run in order, queries may run in parallel, subscriptions stream events.
  • Expect data plus optional errors; model expected failures in the schema.
  • Paginate with cursors, batch with DataLoader, limit cost, and deprecate before removing.

You have reached the end of the tutorial. Test yourself with the Interview Questions or the Practice Exercises.