How it works
The explanation, with examples you can run.
A query with the usual tools
query PostPage($id: ID!, $withComments: Boolean = false) { post(id: $id) { title author { ...AuthorBadge } comments(first: 20) @include(if: $withComments) { edges { node { body author { ...AuthorBadge } } } } } me { name }} fragment AuthorBadge on User { id name small: avatar(size: 64)}- Variables (
$id) are declared with types and sent separately as JSON:{ "id": "p_42", "withComments": true }. - Fragments name a reusable selection; client libraries often colocate one fragment with each component.
- Aliases (
small:) rename a result key and allow the same field twice with different arguments. - Directives
@include(if:)and@skip(if:)drop parts of the selection based on a variable. - On abstract types, inline fragments (
... on Post { title }) select fields per concrete type, and__typenametells the client which one it got.
The server validates the document against the schema before running anything: unknown fields, wrong argument types or a fragment on the wrong type are rejected with no data at all.
Mutations
mutation Publish($input: CreatePostInput!) { createPost(input: $input) { id title publishedAt }}A mutation field returns an object like any other field, so the client can select the updated data and refresh its cache in the same round trip. When one document contains several top-level mutation fields, they run one after another in order. That prevents a race with yourself, but it is not a transaction; if the second fails, the first has already happened.
Subscriptions
subscription OnComment($postId: ID!) { commentAdded(postId: $postId) { id body author { name } }}Each subscription operation must select exactly one root field. The server keeps the request open and sends a result each time an event fires, running the selection for that event. The spec defines the semantics but not the transport; WebSockets and server-sent events are common. Subscriptions are stateful, long-lived connections, which affects scaling, load balancing and authentication in ways queries don't.
Incremental delivery with @defer and @stream, which lets one query return slow parts later, is a proposal still being worked on and not part of a published edition of the spec; some servers support experimental versions.
Check yourself
3 questions. Get them all right to finish this topic.
0 of 3 right so far. Get all three to finish this topic.