Lesson 1 / 25

GraphQL Compared With REST

One endpoint, client-shaped responses.

Over-fetching and under-fetching

With REST, each resource has its own URL and a fixed response shape, so a screen often needs several requests (under-fetching) and receives fields it does not use (over-fetching). GraphQL, created at Facebook and now governed by the GraphQL Foundation, exposes a typed schema at a single endpoint; the client sends a query describing exactly which fields and related objects it wants, and the response mirrors that shape. The schema doubles as documentation and enables tooling such as autocomplete and code generation.

Ask for exactly what you need

GraphQL lets clients describe the data they need in one request against a typed schema.

Three ideas: GraphQL versus REST, the request model, when to use it.
Figure 1.1 — REST versus GraphQL, requests and fit.

One screen, two approaches

Loading a user with recent orders and product names.

REST:
  GET /users/42                    -> full user object (20 fields, we need 2)
  GET /users/42/orders?limit=3     -> 3 orders
  GET /products/7, /products/9 ... -> one request per product name

GraphQL (one request):
  POST /graphql
  { user(id: "42") { name orders(first: 3) { total items { product { name } } } } }

A set menu versus ordering à la carte

REST serves set menus per endpoint; GraphQL lets each diner order exactly the dishes they want from one menu.

Quick check: What problem does GraphQL address directly?

  • TLS encryption
  • Database indexing
  • Over-fetching and under-fetching of data
  • Container orchestration
Answer

Over-fetching and under-fetching of data — Clients choose the fields.