Why you need it

Apps get their data from servers through an API, and the way you ask shapes how fast the app feels. Ask too coarsely and you download data you never show. Ask in too many pieces and a phone on a slow network waits for trip after trip.

Think of it like this

Ordering from a set menu against ordering à la carte. The set menu (REST) is quick to offer, but you get every dish whether you want it or not, and need a second order for dessert. À la carte (GraphQL) means you list exactly what you want, once, and the kitchen does more work.

Where you’ll find it

  • GitHub: Offers both side by side: a REST API and a GraphQL API.
  • Shopify: Builds its shop admin on a GraphQL API, so apps fetch exactly the product fields they need.
  • Stripe: Runs one of the best-loved REST APIs: one clear address for each thing.

What to know first

API. The menu of questions a server will answer, and the exact way to ask each one.

Round trip. One question sent and one answer back. On a phone network each can take 100 ms or more.

Field. One piece of a record, like a user's name or photo.

How it works

  1. REST: one address per thing. Each kind of thing has its own address: /users/7, /users/7/posts. You fetch it with standard verbs like GET and POST, and the server decides what comes back.
  2. REST's two problems. Too much: you need a name, you get all ten fields.Too many trips: a screen showing a user, their posts and their friends needs three requests, one after another. Both are shown in the animation.
  3. GraphQL: one query, exactly what you need. One address. The app sends a query listing the fields it wants, nested as deep as it likes, and gets back exactly that shape in one trip.
  4. GraphQL's costs. Caching is harder, because every request goes to the same address. One careless query can ask for a huge amount of data, so servers must limit how deep or costly a query may be. And the server does more work to put the answer together.
  5. Choosing. REST suits simple and public APIs, and plays well with caches (CDN). GraphQL suits apps with many screens that each need a different slice of the same data. Plenty of companies run both.

An example

A profile screen needs a user's name, their last 3 posts and their friend count.

With REST: /users/7 returns 10 fields (2 KB), /users/7/posts returns 20 full posts (40 KB), /users/7/friends returns the whole list (15 KB). Three trips of about 150 ms each on a phone: nearly half a second, for 57 KB, most of it thrown away.

With GraphQL: one query asks for name, posts(last: 3) { title } and friendCount. One trip, 150 ms, about 1 KB.

Further reading