Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Getting Started

Your First Query

Read and write your first GraphQL query: operations, selection sets and fields, the data and errors envelope, and how a query travels as JSON over POST.

A GraphQL query looks a little like JSON without the values: curly braces, names, nesting. That resemblance is deliberate. You write the shape you want, and the server fills in the values. In this lesson you will learn to read every part of a query, see what the response envelope contains, send a query over HTTP, and build a miniature executor that returns exactly the requested fields.

Reminder: no real GraphQL server runs on this site. Query text and HTTP calls are shown read-only, while the runnable examples use a hand-written stand-in executor.

Anatomy of a query

GRAPHQL
query GetBook {
  book(id: "b1") {
    title
    year
  }
}

Piece by piece:

  • query is the operation type. The other two are mutation (change data) and subscription (listen for events), covered in Mutations and Subscriptions.
  • GetBook is the operation name. It is optional but valuable: it shows up in logs, error messages and developer tools.
  • { ... } is a selection set: the list of fields you want from the current object.
  • book(id: "b1") is a field with an argument. Arguments are in parentheses.
  • title and year are leaf fields: they hold simple values (scalars), so they have no braces of their own.

When the query is the only operation in the request and has no variables, you may use the shorthand and drop the keyword and name:

GRAPHQL
{
  book(id: "b1") {
    title
    year
  }
}

Whitespace and commas between fields do not matter. Comments start with #.

Reading a query

Operation query, mutation or subscription.
Selection set Curly braces listing wanted fields.
Field One piece of data, maybe with arguments.
Leaf A scalar field with no braces.

Every object field needs a selection set; every leaf must not have one.

1 / 2

The response mirrors the query

The server answers with JSON:

JSON
{
  "data": {
    "book": {
      "title": "The Dispossessed",
      "year": 1974
    }
  }
}

Keys appear in the order you asked, and only the fields you asked for are present. Ask for year before title and the keys swap.

The top level is an envelope with up to three keys:

Key Meaning
data The result, shaped like your query. null if the query could not run at all.
errors A list of problems, present only when something went wrong.
extensions Optional extra information, such as tracing; servers decide what goes here.

A response can contain both data and errors: one failing field does not necessarily discard the rest. That is the topic of How Execution Works and How Errors Behave. A query with a mistake the server catches before running (an unknown field, say) gets only errors:

JSON
{
  "errors": [
    {
      "message": "Cannot query field \"colour\" on type \"Book\".",
      "locations": [{ "line": 3, "column": 5 }]
    }
  ]
}

The exact wording of messages differs between server libraries. The message and locations keys are standard.

Sending a query over HTTP

A GraphQL request is, at its simplest, an HTTP POST with a JSON body containing a query string. Here it is with curl and with fetch. These are read-only because there is no server to call from this page:

Terminal
curl -X POST http://localhost:4000/graphql \
  -H "Content-Type: application/json" \
  -d '{"query": "{ book(id: \"b1\") { title year } }"}'
JavaScript
const response = await fetch("http://localhost:4000/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    query: `{ book(id: "b1") { title year } }`,
  }),
});
const { data, errors } = await response.json();

The query travels as a plain string inside the JSON. Inside that string you use double quotes for GraphQL strings, which is why the curl version escapes them. Two more body keys exist, variables and operationName; you will meet them in Variables and Directives and GraphQL over HTTP.

A stand-in: parse, then return exactly what was asked

A real server has two stages we can imitate. First it parses the text into a tree. Then it executes the tree against the data. The code below does both for the subset you have learned so far: nested fields, an optional query keyword and name. (Arguments come in the next lesson.)

Look at what parse produces for the first query, then at how execute uses the tree.

JS Parsing a query into a tree

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

No output.

The tree is what a real server's parser also builds (the real one is called an AST). Now the executor walks that tree over the data and copies out only the named fields. It also produces the data/errors envelope. The checks mimic two real validation rules: a field must exist, and a field holding an object needs a selection set.

JS A mini GraphQL executor

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

No output.

Study the output. Good queries return data with exactly the requested keys, in query order. The broken ones return errors and no data, just like a real server that fails validation. Real servers do much more: they know the types from a schema, validate before running anything, resolve fields with functions instead of properties, and keep going after a single field fails. But the principle, a tree of requested fields guiding what gets read, is how it works.

Give every real query an operation name (query GetBook { ... }) even when the shorthand is allowed. Server logs, monitoring and browser dev tools then show meaningful names instead of "anonymous".

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In query GetBook { book { title } }, what is GetBook?

    The operation name is optional, but it labels the request in logs and tools. The selection set starts at the first curly brace.
  2. 2. What does a response with errors but no data usually mean?

    Validation or syntax problems stop execution before any data is produced, so only errors come back.
  3. 3. How does a client normally send a query over HTTP?

    POST with JSON is the common form. GET is also allowed, mainly for persisted queries, and WebSockets are used for subscriptions.
  4. 4. Which is wrong in GraphQL?

    A scalar leaf field has no subfields, so it cannot have a selection set. The response simply follows whatever order you choose.

Summary

  • A query is an operation (usually query), an optional name and a selection set of fields.
  • Object fields need a selection set; scalar leaf fields must not have one.
  • The response is JSON with a data key shaped like the query and an errors key when something fails.
  • Requests are typically POST with a JSON body containing query (and optionally variables and operationName).
  • A server parses the text into a tree and executes it, copying only the requested fields; the stand-in here does the same in a few lines.

Next: Fields, Arguments and Nested Selections