Tech / Dev

GraphQL Query Sample

Generate GraphQL queries, mutations and subscriptions with variables, fragments and aliases.

Instant🔒In your browserNo signup
Live

What is GraphQL?

GraphQL is a query language for APIs created at Facebook and open-sourced in 2015. The difference vs REST is structural: instead of multiple endpoints (one per resource), there's a single /graphql endpoint that receives queries and returns exactly the requested fields. The client decides what it needs; the server exposes what's possible.

Anatomy of a query

A query starts with the keyword query (optional for simple queries), a name, typed variables ($id: ID!) and the body: root-type fields, sub-fields and arguments. The braces { } define which fields to fetch; without them, none are.

Mutations: when something changes

Mutations modify state. Syntax almost identical to queries, but with the keyword mutation. Convention: imperative names (createUser, deleteOrder) and return the modified object so the client can update its cache without a refetch.

Subscriptions: real time

Subscriptions use WebSockets. Useful for live feeds, notifications, presence. The client opens a connection and receives events when the server publishes. The protocol most used today is graphql-ws.

Variables

Hardcoding values breaks caching and opens injection paths. The right approach is to declare variables: query Get($id: ID!) { user(id: $id) { ... } } and send variables in the request JSON. The server parses them separately.

Fragments

If the same fields appear in several queries, define a fragment: fragment UserFields on User { id name email } and use it with ...UserFields. Apollo and Relay leverage fragments to colocate fields next to the component that uses them.

Aliases and directives

If you ask for the same field twice with different arguments, use an alias: active: users(status: ACTIVE) { id }. Directives @include(if: $cond) and @skip(if: $cond) conditionally include or skip fields based on variables.

The N+1 problem

If you ask for a sub-field on a list (author of each post), a naive resolver fires one query per post. With DataLoader (from Facebook) you batch all IDs in one query and return an array. It's the key tool to keep GraphQL from destroying your database in production.

FAQ

What is GraphQL?

A query language where the client picks exactly which fields it wants. One URL for everything.

GraphQL or REST?

REST wins on simplicity and HTTP caching; GraphQL on client flexibility.

What is a fragment?

A reusable set of fields included via ...Name.

Was this generator useful?