REST, GraphQL and gRPC
medium 26 minThree ways to offer an API.
Video lesson · Chapter 1 of 6
REST and separate resources
REST vs GraphQL vs gRPC
1:19Reel
Theory
Read or listen first. About 2 min.
What it is
REST is an architectural style. The server offers resources at addresses, the client uses HTTP methods on them, and the server decides what each answer contains.
GraphQL is a query language with a typed schema. The client sends one query that names the fields it wants, and the answer has exactly that shape.
gRPC is a framework for remote procedure calls. You describe methods and messages in a file, a tool writes the client and server code, and the messages travel as binary Protocol Buffers over HTTP/2.
Why it exists
The three answer different problems. REST answers: how can strangers use my system with tools they already have? GraphQL answers: how can many different screens get different data without a new endpoint each time? gRPC answers: how can my own services call each other quickly, with types checked on both sides?
Choosing badly costs round trips, unneeded data or difficult integrations. Choosing well starts with the caller, not with fashion.
A short history
2000
Roy Fielding's thesis describes REST as the architectural style behind the web.
July 2008
Google releases Protocol Buffers, its binary message format, as open source.
2012
Facebook creates GraphQL while rebuilding its native mobile apps, whose screens needed nested data in few requests.
February 2015
Google announces gRPC as an open source framework on HTTP/2, following its internal system Stubby.
2015
Facebook publishes GraphQL as an open specification.
August 2016
gRPC 1.0 is declared ready for production. It joins the Cloud Native Computing Foundation in March 2017.
2019
The GraphQL Foundation is formed as a neutral home for the project.
Words to know
- Over-fetching
- Receiving more fields than needed.
- Under-fetching
- Receiving too little, so more requests follow.
- Schema
- The written list of types, fields and operations.
- Resolver
- The function that produces one field in a GraphQL server.
- N+1 problem
- One query for a list, then one more for each item.
- Protocol Buffers
- A binary message format with numbered fields.
- Stub
- Generated client code that looks like a local function.
- Multiplexing
- Many requests sharing one connection at the same time.
How it works
Step through the idea, or press Play.
Who calls it?. Strangers, our own screens, or our own services
Understand it
Start here
The stationery shop
Imagine you need three things from a stationery shop. There are three ways to be served.
Boxes for everyone, a list for those who know what they want, a tube for the staff.
REST
The web's own style. Simple, cacheable, stateless.
GET /users/123/ordersGraphQL
Ask for exactly what you need. One endpoint, typed schema.
{ user(id: 123) { name } }gRPC
Typed calls in binary over HTTP/2, with streams and generated code.
users.GetUser(123)
REST
REST: resources with addresses
Standard HTTP methods act on resources named by URLs. How that works is told in API design introduction.
GET /api/v1/users/123/orders HTTP/1.1Host: api.shopeasy.exampleAuthorization: Bearer fake-tokenAccept: application/jsonHTTP/1.1 200 OKContent-Type: application/json{ "orders": [ { "id": "ORD-001", "total": 99.99 }, { "id": "ORD-002", "total": 149.99 } ] }Over-fetching: the screen only shows the name
| Field in GET /users/123 | Needed |
|---|---|
| id: 123 | No |
| name: Asha Rao | Yes |
| email: asha@example.com | No |
| phone, address, preferences | No |
| created_at, last_login | No |
Under-fetching: one screen, four requests
REST strengths
- Simple and intuitive
- HTTP caching works as it is
- Stateless, so easy to scale out
- Tools everywhere: curl, Postman, OpenAPI
- Works in every browser
- Most developers know it
REST weak spots
- Over-fetching
- Under-fetching, several requests
- No built-in push
- Versioning needs a plan
- No single standard for filters and paging
- Types and docs are extra work (OpenAPI helps)
GraphQL
GraphQL: ask for what you need
POST /graphqlquery { user(id: 123) { name orders(limit: 3) { id total items { product { name } } }} }200 OK{ "data": { "user": { "name": "Asha Rao", "orders": [ { "id": "ORD-001", "total": 99.99, "items": [ { "product": { "name": "Headphones" } } ] } ] } } }Three operations
| Operation | Purpose | Example |
|---|---|---|
| Query | Read, like GET | query { products { name price } } |
| Mutation | Write, like POST, PUT or DELETE | mutation { createOrder(input: {...}) { id } } |
| Subscription | Updates pushed as they happen | subscription { orderUpdated { status } } |
How a server answers one query
GraphQL strengths
- No over-fetching, fewer requests
- One endpoint
- Strong types in a schema
- Self-describing (introspection)
- Subscriptions in the language
- Can grow without versions: add fields, deprecate old ones
GraphQL weak spots
- More to learn
- HTTP caching is harder
- Resolvers need batching
- Clients can write expensive queries
- Needs its own tools and permissions per field
- Too much for a simple API
The N+1 problem
gRPC
gRPC: call a method on another machine
// user.proto: the shared contractsyntax = "proto3";service UserService { rpc GetUser(GetUserRequest) returns (User); rpc ListOrders(ListOrdersRequest) returns (stream Order);}message GetUserRequest { int32 user_id = 1; }message ListOrdersRequest { int32 user_id = 1; }message User { int32 id = 1; string name = 2; string email = 3; }message Order { string id = 1; int64 total_cents = 2; }# Python client, using generated code (no TLS: local test only)channel = grpc.insecure_channel("localhost:50051")client = user_pb2_grpc.UserServiceStub(channel)user = client.GetUser(user_pb2.GetUserRequest(user_id=123), timeout=0.5)print(user.name) # Asha RaoFour kinds of call
| Kind | Messages | Good for |
|---|---|---|
| Unary | one request, one response | Ordinary calls |
| Server streaming | one request, many responses | A live feed, a long list |
| Client streaming | many requests, one response | Uploading in parts |
| Bidirectional | both sides, any time | Chat, games |
Unary, then server streaming, on one connection
Why it is efficient
Binary messages
Field numbers instead of names, numbers as bytes. Smaller, and quick to read.
HTTP/2
Many calls share one connection at the same time.
Generated code
Client and server are written by a tool from the same file. Parsing still happens, but is quick and typed.
One user, counted in bytes
gRPC strengths
- Compact and fast
- Multiplexing over HTTP/2
- Streams in both directions
- Generated clients and servers
- Types enforced by the .proto file
- Many languages
gRPC weak spots
- Browsers need gRPC-Web and a translating proxy or server
- Binary, not readable by eye
- More to learn
- Fewer everyday tools than REST
- Harder to debug by hand
- Long connections need a balancer that understands HTTP/2
Compare
Side by side
Features
| REST | GraphQL | gRPC | |
|---|---|---|---|
| Transport | Any HTTP version | Usually HTTP | HTTP/2 |
| Format | Usually JSON | JSON | Protobuf (binary) |
| Endpoints | Many URLs | One | Many methods |
| Types | Optional (OpenAPI) | Schema | .proto file |
| Caching | HTTP, built in | In the client, or GET with saved queries | Your own |
| Real time | Polling, SSE, WebSocket beside it | Subscriptions | Streams |
| Browser | Native | Native (it is HTTP) | gRPC-Web and a translator |
| To learn | Little | Some | More |
| Best for | Public APIs | Screens with mixed data | Service to service |
If you need
| Need | REST | GraphQL | gRPC |
|---|---|---|---|
| Public API | very good | possible | rare |
| Complex screens | possible | very good | weak |
| Microservices | possible | possible | very good |
| HTTP caching | very good | weak | weak |
| Real time | weak alone | good | very good |
| Browser without extras | very good | good | weak |
Which one?
Numbers
Count round trips, not slogans
The profile screen needs the user, three orders and the product names. Assume a 100 ms round trip on mobile, an open connection, and 20 ms of server work per wave.
| Way | Waves | Time |
|---|---|---|
| REST, one after another | 4 | 4 x 120 = 480 ms |
| REST, parallel where possible | 2 | 2 x 120 = 240 ms |
| REST, one endpoint for this screen | 1 | about 120 ms |
| GraphQL, one query | 1 | about 120 ms |
| gRPC, one method for this screen | 1 | about 120 ms |
Time for a screen
Together
Use more than one
Three styles in one system
- REST at the edge for partners, with keys and caching.
- GraphQL for our apps, as a thin layer that combines services.
- gRPC inside, with deadlines and generated clients.
- A gateway can translate JSON to gRPC, so one service serves both: API gateway.
Change
How each one evolves
| Add | Remove | Danger | |
|---|---|---|---|
| REST | New optional fields and endpoints | New version, or a long deprecation | Clients that reject unknown fields |
| GraphQL | New fields and types | @deprecated, watch usage, then remove | Forgetting that unknown clients remain |
| gRPC | New fields with new numbers | Reserve the old number and name | Reusing a field number: old clients misread it |
Operate
What breaks in production
- 1
REST: chatty clients
A list view calls the item endpoint for every row. Fix: include the needed fields, or one endpoint per screen.
- 2
GraphQL: one slow field
One field makes a whole query slow. Fix: trace per resolver, timeouts, batching.
- 3
gRPC: uneven load
A long connection sticks to one server, so a new server stays idle. Fix: balance per request, or limit connection age.
- 4
All: no deadline
Calls wait forever and pile up. Fix: timeouts.
Summary
The whole topic in one minute.
REST: addresses, methods and HTTP caching, understood by everyone. GraphQL: one query with exactly the fields you want, and a server that must protect itself from expensive queries. gRPC: typed methods, small binary messages and streams, best between services you control.
Compare them by the caller, the shape of the data, caching, and what the team can operate. Count round trips instead of quoting speed claims. A system may use REST at the public edge, GraphQL for its own apps and gRPC inside.
- REST for public APIs: simple, HTTP caching, known by everyone.
- GraphQL for screens with mixed data: exactly the fields, one request.
- gRPC between services: typed, compact, streams in both directions.
- REST can over-fetch and under-fetch. GraphQL moves the work to the server.
- Protobuf is binary: smaller, but not readable by eye.
- Use several styles in one system, each at its boundary.