Card 02/ 09

ConceptDifficulty: Beginner1 min

GraphQL: The Client Chooses the Fields

One endpoint, a schema of types, and a query that names exactly the fields the screen needs.

GraphQL is a query language for APIs, specified by the GraphQL Foundation. The server publishes a schema, a set of types and the fields on each, and exposes one endpoint, usually POST /graphql. The client sends a query naming exactly the fields it wants, and the response has the same shape as the query. Reads are queries; changes are mutations.

json
{
  "query": "{ order(id: \"7\") { id status items { name quantity } } }"
}

{
  "data": {
    "order": {
      "id": "7",
      "status": "SHIPPED",
      "items": [
        { "name": "Kettle", "quantity": 1 },
        { "name": "Mug", "quantity": 4 }
      ]
    }
  }
}
An illustrative query, sent as a string in the request body, and the response with the same shape

The schema is the contract. Every type and field is declared, so tools can check a query before it is sent and generate typed client code. Fields are added freely and old ones are marked deprecated, which is why many GraphQL APIs never publish a version 2.

Errors look different. A query that partly fails still commonly returns 200 OK, with the data it could resolve and an errors array describing the rest. Clients must read the body, not only the status code.

Caching changes. Every query goes to the same URL by POST, so HTTP caches and CDNs cannot cache responses by URL the way they cache GET /orders/7. GraphQL APIs cache in the client, by object id, or use persisted queries sent by GET.

The server pays for flexibility. The client chooses the shape, so the server must guard against queries that are expensive to resolve, which the topic's gotcha covers.

So GraphQL suits clients with varied needs, at the cost of HTTP caching and of guarding the server.