Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 37 ยท Getting Started

GraphQL vs REST

Compare GraphQL and REST with the same data: round trips, payload size, versioning, caching and tooling, plus when plain REST is still the better choice.

GraphQL and REST are both ways to build an HTTP API, and neither is "the winner". They make different trade-offs. REST gives you many URLs, each returning a fixed resource. GraphQL gives you one URL and a language for asking for exactly the fields you want. This lesson puts them side by side on the same data so you can see the differences in numbers, not slogans.

If you have not built a REST API yet, REST APIs in Node.js explains the basics we compare against. For the GraphQL side, you only need What Is GraphQL?.

The same screen, two ways

Our screen is an author page. It must show the author's name, each of their books' titles, and the star rating of every review of each book. With REST that data usually lives behind several endpoints:

TEXT
GET /authors/a1            -> the author
GET /authors/a1/books      -> that author's books
GET /books/b1/reviews      -> reviews of book 1
GET /books/b2/reviews      -> reviews of book 2
GET /books/b3/reviews      -> reviews of book 3

With GraphQL the same screen is one request:

GRAPHQL
{
  author(id: "a1") {
    name
    books {
      title
      reviews { stars }
    }
  }
}

The next stand-in builds both versions over the same data. Its rest() function is a fake server that counts every request and every byte it returns. The GraphQL half uses a small selection walker like the one from the previous lesson (a stand-in for a real GraphQL server).

JS Counting round trips and bytes

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

No output.

Read the numbers carefully. GraphQL needs one round trip against REST's five, and the response is far smaller, because REST sent ISBNs, publishers, review texts and a biography that this screen never uses. On a fast office network the difference may be invisible. On a phone with a weak signal, five sequential round trips (the review requests cannot start until the book list arrives) are very noticeable.

REST can close this gap too: a server may add ?include=books.reviews, a fields= parameter or a purpose-built /author-page/a1 endpoint. Those patterns work, but each one is a design decision per endpoint. GraphQL makes "choose your fields and relationships" a standard feature of every field.

Over-fetching and under-fetching in depth

You met both words in the first lesson; now let us take them apart carefully, because they are the most quoted reason for choosing GraphQL and also the most misunderstood.

Over-fetching means the response contains more data than the screen uses. A book list row shows a title, but GET /books/b1 returns the description, ISBN, publisher and cover URL too. The extra bytes cost bandwidth, parse time and battery, and they also make caching harder because a change in any unused field invalidates the response.

Under-fetching means one response is not enough, so the client makes more requests. The book detail page needs the author's name, but the book only holds an authorId, so a second request, GET /authors/a1, must wait for the first to finish. The requests are dependent (the second needs data from the first), so the delay adds up: three levels of nesting mean three sequential round trips, each paying for latency, TLS and server queueing.

The two problems pull in opposite directions, which is why they are so annoying with fixed endpoints. Make the endpoint richer to avoid under-fetching, and it over-fetches for the screens that need less. Make it leaner, and the screens that need more must make extra requests.

Worked example: three screens, one resource

The stand-in below models three screens that need different parts of the same book. It measures, for each screen, the bytes a fixed REST resource sends, the number of requests, and the bytes the screen truly needs (what a GraphQL query for exactly those fields would return). The sizes are real JSON lengths, so you can see the ratio.

Node.js Bytes sent versus bytes needed

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The list row receives about nine times more data than it shows. The share card needs two fields from the book and one from the author, yet receives everything and costs two sequential requests. Multiply that by a list of fifty rows on a slow mobile connection and the difference becomes visible to users.

How REST teams solve it

Over- and under-fetching are not unique to GraphQL's world; REST APIs have standard workarounds, each with a price:

Technique What it solves The catch
Sparse fieldsets (?fields=id,title) Over-fetching Every endpoint must implement it; the convention varies
Embedding or expansion (?include=author, ?expand=author) Under-fetching Nested shapes still fixed by the server; parameters multiply
Purpose-built endpoints (/book-detail-page/b1) Both, for one screen Endpoints pile up, and each screen change needs a back-end change
Backend-for-frontend Both, per client type More servers to run; still fixed per screen
JSON:API, OData Standardized fields and includes Heavier conventions to learn

These all work, and a well-designed REST API with sparse fieldsets and includes can be perfectly good. GraphQL builds the same capabilities into the language: every field is selectable, every relation can be nested, and the rules are the same for the whole API, so the client team does not wait for a new parameter.

What GraphQL solves, and what it does not

GraphQL removes client-visible over-fetching because the response contains only the selected fields, and removes client-visible under-fetching because relations nest in a single request. Three honest caveats keep this fair:

  • The server may still over-fetch internally. A resolver that loads a whole database row to return two columns, or calls a service per field, shifts the waste from the network to the back end. Good servers look at the selected fields or batch loads (see N+1 and DataLoader).
  • Clients can ask for too much. A query that nests six levels and asks for every field can be far more expensive than any REST call, which is why limits exist.
  • One big query is not always better than three small ones. Parallel requests over HTTP/2 and a good cache can beat a single large query that is hard to cache. Measure with your own data.

A good rule: when your screens differ a lot in what they need, or when mobile bandwidth and latency matter, the flexibility of GraphQL pays. When a few stable endpoints serve every client well, REST with a sparse-fieldset convention is simpler.

Versioning: v2 or "just add a field"

REST APIs often change by publishing /v2/, because removing or renaming a field breaks clients that depended on it. GraphQL clients name every field they use, so the server can see which fields are still in use. The usual approach is to add new fields freely (old queries do not notice) and to mark old ones deprecated before removing them. Run this to see an old query keep working after the data gains a new field.

JS Adding a field breaks nobody

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

No output.

A fair comparison

Topic REST GraphQL
Endpoints Many, one per resource Usually one (/graphql)
Response shape Fixed by the server Chosen by the client
Related data Extra requests or custom endpoints Nested in one query
Versioning Often /v1, /v2 Evolve the schema, deprecate fields
HTTP caching Excellent: GET URLs, ETags, CDNs Harder: usually POST, needs extra work
Errors HTTP status codes Usually 200 with an errors list
Tooling OpenAPI/Swagger Typed schema, introspection, GraphiQL
File uploads, streaming downloads Natural Awkward, usually done outside GraphQL
Learning curve Low Higher (schema, resolvers, N+1, security)

Two rows deserve extra explanation.

Caching. A REST GET /books/1 is cached by browsers and CDNs for free, because the URL identifies the resource. A GraphQL query travels in a POST body, which generic caches ignore. There are good solutions (persisted queries over GET, client-side normalized caches, response caching on the server), covered in Caching and Performance, but they take work that REST gets by default.

Errors. REST reports failure through the HTTP status (404, 500). GraphQL can return partial data with an errors list, so one failing field does not discard the rest of the answer. This is powerful and surprising at first; How Execution Works and How Errors Behave covers it.

When REST is still the better choice

Pick plain REST (or even simpler options) when:

  • The API is small and has one or two clients with predictable needs.
  • You serve files, images, video or other binary content.
  • You depend heavily on CDN or browser caching of public resources.
  • Your team has strong REST tooling and no appetite for new operational concerns, such as query cost limits.
  • You are exposing a public API to many unknown developers who expect resource URLs and API keys.

Pick GraphQL when many clients need different shapes of the same data, screens combine several backend services, or front-end teams want to iterate without waiting for new endpoints. Many companies use both: GraphQL for the application front end, REST for webhooks and partner integrations.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why did the REST version of the author page need five requests?

    Resources live behind separate endpoints. The review requests also depended on the book list, so they could not start in parallel with it.
  2. 2. How does GraphQL typically avoid '/v2' style versioning?

    Because each query lists the fields it uses, adding fields is safe and usage of deprecated fields can be tracked before removal.
  3. 3. Which is usually harder with GraphQL than with REST?

    GraphQL queries normally use POST to one URL, which generic caches do not cache. Persisted queries and client caches fill the gap.
  4. 4. Which case favors plain REST?

    Files and publicly cacheable resources fit REST's URL-per-resource model well.

Summary

  • REST exposes many resource URLs with fixed shapes; GraphQL exposes one endpoint where the client picks fields and relationships.
  • GraphQL can replace several sequential round trips with one request and avoid sending unused fields.
  • GraphQL evolves by adding and deprecating fields rather than publishing new API versions.
  • REST has a head start on HTTP caching, file handling and simplicity.
  • Errors differ: HTTP status codes in REST, partial data plus an errors list in GraphQL.
  • Choose by need, and remember that using both in one system is common.

Next: Your First Query