What GraphQL is

GraphQL · Essentials · 8 min

Knowing what GraphQL does (and does not) solve tells you when to pick it over REST or gRPC.

GraphQL is a query language for APIs plus a runtime that executes those queries against a typed schema. A GraphQL API usually lives at one endpoint such as /graphql. Instead of many URLs returning fixed payloads, the client sends a document describing the data it needs, and the server returns JSON with exactly that shape.

Three ideas carry everything else:

  • The schema is the contract. Every type, field and argument is declared, so tools can validate queries, autocomplete them and generate typed client code.
  • Clients choose fields. A mobile screen and a desktop dashboard can ask the same API for different subsets, avoiding over-fetching (too much data) and under-fetching (several round trips).
  • The response mirrors the query. Nested selections become nested JSON objects, under a top-level data key, with problems listed under errors.

GraphQL is transport-agnostic, but in practice it runs over HTTP with JSON. It is a specification, not a product: graphql-js is the reference implementation, and servers exist for every major language.

Trade-offs to know up front: HTTP caching is harder than with REST because most requests are POSTs to one URL, a careless schema can let clients write very expensive queries, and file uploads and streaming need extra conventions. GraphQL shines when many clients consume rich, connected data.

Example

# One request, nested data, exactly the requested fields
query {
  user(id: "42") {
    name
    posts(first: 2) {
      title
    }
  }
}

# Response (same shape as the query)
# {
#   "data": {
#     "user": {
#       "name": "Ann",
#       "posts": [{ "title": "Hello" }, { "title": "GraphQL notes" }]
#     }
#   }
# }

Remember

  • One endpoint, one typed schema, client-chosen fields
  • Responses have the same shape as the query, under data
  • It is a spec; graphql-js is the reference implementation

Watch out for

  • Assuming GraphQL is a database query language; it sits in front of any data source.

Check yourself

  1. What problem does letting clients select fields mainly address?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: graphql.org/learn/

Builds on

Nothing: this is a foundation.

Unlocks