Queries are the heart of GraphQL: declarative descriptions of the data your UI needs, sent to a single endpoint and answered with JSON of exactly the same shape. In this lesson we will write real queries, nest them, alias duplicate fields, and learn how GraphQL responses behave when things go wrong.
A query is a selection of fields starting from the Query root type. Given the blog schema from the previous lesson:
query GetUsers {
users {
id
name
}
}A few things to note:
query is the operation type; GetUsers is an optional but recommended operation name that shows up in logs and dev tools.SELECT * in GraphQL, and that is a feature.data key mirroring your selection.{ "data": { "users": [{ "id": "1", "name": "Ada" }] } }Because fields can return object types, selections nest arbitrarily deep. This is how one request replaces several REST round trips:
query PostWithAuthor {
post(id: "7") {
title
author {
name
posts {
title
published
}
}
}
}The server walks the graph for you: post 7, its author, and the other posts by that same author, all in one round trip. Be aware that depth has a cost; production servers usually enforce a maximum query depth to stop abusive requests.
JSON keys must be unique, so you cannot ask for post(id: "7") and post(id: "9") side by side without renaming one. Aliases solve this:
query TwoPosts {
first: post(id: "7") { title }
second: post(id: "9") { title }
}The response now uses your names: { "data": { "first": {...}, "second": {...} } }. Aliases are also handy for renaming server fields to what your UI component expects.
Lines starting with # are comments. Whitespace and commas are insignificant, so format for readability; most teams run Prettier on .graphql files.
A GraphQL response can contain both data and errors. If resolving one nullable field fails, the server nulls that field, appends an entry to the errors array with a path, and still returns everything else:
{
"data": { "post": { "title": "On Engines", "viewCount": null } },
"errors": [{ "message": "stats service timeout", "path": ["post", "viewCount"] }]
}Partial success is a deliberate design choice: one flaky microservice should not blank out the whole screen. We will go much deeper on errors in lesson 11.
Most GraphQL servers ship an in-browser IDE, GraphiQL or Apollo Sandbox, at their endpoint. Thanks to schema introspection you get autocomplete (Ctrl+Space), inline docs, and instant execution. Make it a habit: explore any new GraphQL API through its playground before writing application code.
Query root; the response mirrors its shape under data.data and errors can coexist.Next lesson: Arguments and Variables, where queries become dynamic and reusable.