Skip to content

Module 01 // FoundationsLesson 04 / 3418 min read

APIs: REST, GraphQL, gRPC, WebSockets

An API is the agreed way programs ask each other for data or actions. REST, GraphQL, gRPC and WebSockets are four common styles, each good at different jobs.

Think of it like this

Analogy

An API is a restaurant menu. You don't walk into the kitchen; you order from the menu and the kitchen sends out the dish.

  • REST is a set menu: each dish has a fixed name and comes as the kitchen plates it.
  • GraphQL is ordering à la carte: “the salmon, sauce on the side, no potatoes”, all on one ticket.
  • gRPC is the kitchen's internal shorthand between cooks: fast and compact, but you need to know the codes.
  • WebSockets are a waiter who stays at your table and brings things as soon as they're ready, without you asking again.

The problem it solves

Without a clear API, every client talks to your system differently, and every change breaks someone. You also pay for the wrong style: a mobile app on a slow network making ten requests per screen, a chat app checking for new messages every second, or internal services wasting CPU turning JSON back and forth.

A real example

Example

A food delivery app’s order screen

You open an order in a delivery app. The app calls a REST endpoint, GET /orders/8812, and gets back JSON with the items, the price and the restaurant.

The map with the driver's live position doesn't poll. The app keeps a WebSocket open, and the server pushes a new location every few seconds.

Behind the scenes, the order service asks the payment service and the dispatch service for details. Those are internal calls between the company's own services, thousands per second, so they use gRPC, which is compact and fast and has strict contracts. Three styles of API in one screen, each picked for its job.

How it works

REST: resources and HTTP methods

REST uses HTTP as it was designed. URLs name things (resources) and methods say what to do with them.

Method and pathMeaningSafe to repeat?
GET /users/7Read user 7Yes
GET /users/7/posts?limit=20Read user 7's latest 20 postsYes
POST /postsCreate a new postNo, unless you send an idempotency key
PUT /posts/99Replace post 99Yes
PATCH /posts/99Change some fields of post 99Depends
DELETE /posts/99Delete post 99Yes

REST is simple, cacheable (GET responses can be cached by browsers and CDNs) and understood by every tool. Its weak spot is over-fetching (getting fields you don't need) and under-fetching (needing several requests for one screen).

Pagination. Never return an unbounded list. Use a cursor: GET /posts?limit=20&after=abc123, where the cursor marks the last item seen. Cursors stay correct when new items arrive; page numbers don't.

Versioning. Put a version in the path (/v2/users) or a header so you can change the API without breaking old clients.

GraphQL: the client asks for exactly what it needs

GraphQL has one endpoint. The client sends a query describing the shape it wants:

query {
  user(id: 7) {
    name
    posts(last: 3) { title likeCount }
  }
}

The response matches that shape exactly. It's great for apps with many different screens and for mobile clients on slow networks. The costs: HTTP caching is harder (everything is a POST to one URL), a single query can accidentally ask for a huge amount of data, and the server needs care to avoid making one database query per item (the “N+1” problem).

gRPC: fast calls between services

gRPC defines services and messages in a .proto file and generates client and server code in many languages:

service Orders {
  rpc GetOrder (GetOrderRequest) returns (Order);
}

Messages are compact binary (Protocol Buffers) sent over HTTP/2, so calls are small and fast, and the contract is enforced by the compiler. It also supports streaming in both directions. Browsers can't call gRPC directly without a proxy, so it's mostly used between backend services.

WebSockets: a connection that stays open

HTTP is request–response: the server can only answer. A WebSocket starts as an HTTP request, then upgrades to a long-lived, two-way connection. Either side can send a message at any time. That's what chat, live dashboards, multiplayer games and collaborative editors need.

Each open connection uses memory on the server, and connections are tied to one server, so scaling WebSockets needs care: a load balancer that supports them, and a way to deliver a message to whichever server holds the recipient's connection (lesson 27).

Lighter alternatives: Server-Sent Events (a one-way stream from server to browser over plain HTTP) and long polling.

Architecture
Loading diagram…
One product, four styles: the browser uses REST and a WebSocket, the mobile app uses GraphQL, and internal services talk over gRPC.
  • Web app to API gateway: REST
  • Web app to Realtime server: WebSocket
  • Mobile app to API gateway: GraphQL
  • API gateway to Orders service: gRPC
  • API gateway to Users service: gRPC

Choosing

You needPick
A public API many developers will useREST
Many client screens with different data needsGraphQL
Fast, typed calls between your own servicesgRPC
The server to push updates in real timeWebSockets (or Server-Sent Events for one-way)

Trade-offs

What you gain

  • REST: simple, cacheable, works everywhere.
  • GraphQL: one round trip per screen, no over-fetching, a typed schema.
  • gRPC: small, fast messages, generated clients, streaming.
  • WebSockets: instant two-way updates with no polling.

What it costs you

  • REST: several requests per screen, and fields you don't need.
  • GraphQL: harder caching and rate limiting; expensive queries need limits.
  • gRPC: not browser-native; binary messages are harder to inspect.
  • WebSockets: stateful connections are harder to load-balance and scale.

When not to use it

  • Don't use GraphQL just because it's popular if a handful of REST endpoints would do.
  • Don't use WebSockets for data that changes every few minutes; plain requests or Server-Sent Events are simpler.
  • Don't expose gRPC to third-party developers who expect plain HTTP and JSON.

In the cloud

API gatewayEvery major cloud sells this as a managed service, so you configure it rather than build it.

AWS1

Azure1

Google Cloud2

How you’d set it up

Clients call one gateway; it checks auth and limits, then routes each API to the right backend.

  1. Client
  2. Amazon API Gateway
  3. Lambda or ECS services

Interview questions

Try answering out loud first, then open the model answer.

Design the API for a simple to-do app.

Model answer

I'd use REST. Resources: GET /lists, POST /lists, GET /lists/{id}/items?limit=50&after=cursor, POST /lists/{id}/items, PATCH /items/{id} to rename or mark done, DELETE /items/{id}. Responses return JSON with the created ID and timestamps. Auth with a bearer token in the Authorization header. Creating items accepts an Idempotency-Key header so retries don't duplicate. I'd version under /v1, use cursor pagination, and return 400 for bad input, 401 or 403 for auth problems, 404 for missing items and 429 when rate limited.

When would you choose GraphQL over REST, and what problems does it bring?

Model answer

When many clients need different slices of the same data, especially mobile apps where each extra round trip hurts, or when the front-end team iterates fast and doesn't want a new endpoint for every screen. Problems: caching is harder because responses vary per query; clients can write very expensive queries, so you need depth and cost limits; resolvers can trigger N+1 database queries without batching (a DataLoader); and monitoring is per field rather than per URL.

How would you push live updates to 1 million connected users?

Model answer

Keep one long-lived connection per client, using WebSockets or Server-Sent Events, spread across many connection servers behind a load balancer that supports long-lived connections. Each server holds tens of thousands of connections and subscribes to a pub/sub system for the topics its users care about. When an update happens, it's published once; each connection server pushes it to its local subscribers. Clients reconnect with backoff and catch up on anything missed using a last-seen ID.

Quiz

Pick an answer to see whether it’s right and why.

  1. 01A mobile app shows a profile screen that needs a user's name, their last 3 posts and each post's like count. With a plain REST API this takes 5 requests. Which style lets it ask for exactly that in one request?
  2. 02Which style suits a live chat where the server must push new messages instantly?
  3. 03Two internal services exchange thousands of small calls per second and are both written by your team. What's a strong choice?
  4. 04In REST, which method should be safe to repeat without changing anything?
  5. 05A client retries `POST /payments` after a timeout and the customer is charged twice. What API feature prevents this?
  6. 06You need to change a field's type in a public API that thousands of apps use. What's the safe approach?
  7. 07An endpoint returns 1 million orders in one response and times out. What's the standard fix?

0 of 7 answered

Key terms

API
A defined way for one program to ask another for data or actions.
REST
An API style built on HTTP where URLs name resources and methods (GET, POST, PUT, DELETE) act on them.
GraphQL
An API style where the client sends a query describing exactly which fields it wants, to one endpoint.
gRPC
A fast API style for service-to-service calls that sends compact binary messages over HTTP/2.
WebSocket
A long-lived, two-way connection so the server can push messages to the client at any time.
HTTP
The request–response language browsers and servers speak, with methods like GET and POST and status codes like 200 and 404.

Progress is saved in this browser only.