Expert · Choosing a stack and getting hired · topic 53 of 54 · 30 min
Beyond REST: GraphQL, WebSockets and webhooks
Explanation
Where REST is not enough
In REST, the server decides what each URL returns. Sometimes it sends too much (over-fetching: the whole restaurant with its menu when you only wanted the name). Sometimes too little (under-fetching: you need three requests to build one screen). And REST only answers when asked, so it cannot push news to you the moment it happens.
GraphQL: ask for exactly what you need
GraphQL is a query language for APIs. There is usually one endpoint (POST /graphql). A schema describes every type and field the API offers. The app sends a query that names the fields it wants, and the reply has the same shape. A resolver is the server function that fetches the data for one field.
type Restaurant {
id: ID!
name: String!
city: String!
rating: Float
menu: [Dish!]!
}
type Dish {
name: String!
price: Int!
}
type Query {
restaurant(id: ID!): Restaurant
}# The query the app sends
query {
restaurant(id: "42") {
name
city
}
}
# The reply: only the fields that were asked for
{ "data": { "restaurant": { "name": "Sharma Dhaba", "city": "Pune" } } }GraphQL has costs too. HTTP caching is harder because everything goes to one URL. A client can send a very deep, expensive query, so servers limit query depth and cost. Use it when many different screens or apps need different slices of the same data.
WebSockets and Server-Sent Events
A WebSocket starts as a normal HTTP request with an Upgrade header, then turns into a two-way connection that stays open. Both sides can send messages at any time. It suits chat, a delivery partner moving on the map, and multiplayer games. Server-Sent Events (SSE) keep a plain HTTP response open and let only the server send. The browser reads it with EventSource and reconnects by itself. SSE suits a live cricket score, notifications and streaming AI text.
// WebSocket: two-way
const socket = new WebSocket('wss://example.com/live');
socket.addEventListener('open', () => {
socket.send(JSON.stringify({ type: 'subscribe', matchId: 123 }));
});
socket.addEventListener('message', (event) => {
const update = JSON.parse(event.data);
console.log(update.score); // for example "IND 182/4 (18.2)"
});
// Server-Sent Events: server to browser only
const feed = new EventSource('/api/matches/123/stream');
feed.onmessage = (event) => console.log(JSON.parse(event.data));Webhooks: the other server calls you
- You give the payment gateway a URL on your server, for example https://yourshop.in/api/webhooks/payments, and it gives you a webhook secret.
- When a payment succeeds, the gateway sends a POST request with JSON to that URL.
- It adds a signature header: an HMAC-SHA256 of the raw request body, made with the shared secret. HMAC is a code that only someone with the secret can produce.
- Your server computes the same HMAC over the raw body and compares. If it does not match, reply 400 and stop.
- Reply 200 quickly (within a few seconds). Do slow work, like emails and invoices, in a background job.
- If your server is slow or down, the gateway retries, so the same event can arrive twice. Save each event id and skip ids you have already processed. This makes the handler idempotent: running it twice has the same effect as once.
gRPC is another style, used mostly between services inside one company. You describe methods and messages in a .proto file, a tool generates client and server code, and data travels in a compact binary format over HTTP/2. It is fast and strictly typed, but browsers cannot call it directly without a helper, so public APIs still use REST or GraphQL.
When to use which
| Need | Good choice | Example |
|---|---|---|
| Normal create, read, update, delete | REST | GET /api/orders/91 |
| Many screens need different fields of the same data | GraphQL | A food app home page, menu page and admin app |
| Both sides send live messages | WebSocket | Chat, delivery partner location |
| Only the server pushes updates | Server-Sent Events | Live cricket score, order status, AI text streaming |
| Another company tells you something happened | Webhook | Payment captured, refund done, SMS delivered |
| Fast calls between your own services | gRPC | Order service asks the pricing service for a price |
Watch the lesson
Beyond REST: GraphQL, WebSockets and webhooks · 1/7
REST is the default for APIs. Today we look at four tools for jobs REST does badly.
Prefer a video by a teacher? Find free videos on “rest vs graphql vs websockets vs webhooks explained” on YouTube ↗
In real life: A food delivery order, four technologies
When you order dinner, the app calls a REST endpoint to place the order. You pay through a payment gateway; the gateway then sends a webhook to the food company's server, which verifies the signature, marks the order paid and replies 200 within a second. Restaurant updates such as 'Preparing' reach your phone over Server-Sent Events or a WebSocket, and the moving map of the delivery partner comes over a WebSocket. Inside the company, the order service may ask the pricing and delivery-time services over gRPC.
Practice (0/3 done)
Write select(obj, fields) like a tiny GraphQL resolver. It returns a NEW object with only the keys listed in fields, in the order of fields. Skip any field that the object does not have. Do not change obj.
A payment gateway sends a webhook with a hex signature: the HMAC-SHA256 of the raw body, made with your webhook secret. Write async function verifyWebhook(rawBody, signature, secret) that returns true only when the signature matches. Use crypto.subtle.importKey and crypto.subtle.sign, turn the result into lowercase hex, and compare it with signature.
You are designing a cab booking app. For each feature, choose REST, GraphQL, WebSocket, Server-Sent Events, webhook or gRPC, and give one reason: (1) sign up, (2) the driver moving on the map, (3) payment success from the payment gateway, (4) a "ride status" banner that changes from Searching to Arriving, (5) the trip service asking the fare service for a price.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.