Skip to content

Expert · Choosing a stack and getting hired · topic 53 of 54 · 30 min

Beyond REST: GraphQL, WebSockets and webhooks

Explanation

REST covers most APIs, but some jobs need other tools. GraphQL lets the app ask for exactly the fields it needs. WebSockets and Server-Sent Events push live updates like a cricket score. Webhooks let another service, such as a payment gateway, call your server when something happens.

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.

Think of it like this: REST is like phoning a shop each time you want something. Polling is calling every 10 seconds to ask "Is my parcel ready?". A WebSocket is a phone call that stays open, so either side can talk at any time. Server-Sent Events are like a radio: the station keeps talking, you only listen. A webhook is telling the shop "call me when the parcel arrives" and putting the phone down.

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.

output
type Restaurant {
  id: ID!
  name: String!
  city: String!
  rating: Float
  menu: [Dish!]!
}

type Dish {
  name: String!
  price: Int!
}

type Query {
  restaurant(id: ID!): Restaurant
}
A GraphQL schema. The ! means "never null". [Dish!]! means a list of dishes.
output
# 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" } } }
The app asked for name and city only, so the menu and rating are not sent.

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.

javascript
// 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));
Runs in the browser. The server side needs its own WebSocket or SSE code.

Webhooks: the other server calls you

  1. 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.
  2. When a payment succeeds, the gateway sends a POST request with JSON to that URL.
  3. 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.
  4. Your server computes the same HMAC over the raw body and compares. If it does not match, reply 400 and stop.
  5. Reply 200 quickly (within a few seconds). Do slow work, like emails and invoices, in a background job.
  6. 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.
Careful: Never mark an order as paid only because the browser was redirected to a "success" page; anyone can open that URL. Trust the verified webhook (or ask the gateway API directly). Always check the signature over the exact raw body, before parsing or changing it.

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

NeedGood choiceExample
Normal create, read, update, deleteRESTGET /api/orders/91
Many screens need different fields of the same dataGraphQLA food app home page, menu page and admin app
Both sides send live messagesWebSocketChat, delivery partner location
Only the server pushes updatesServer-Sent EventsLive cricket score, order status, AI text streaming
Another company tells you something happenedWebhookPayment captured, refund done, SMS delivered
Fast calls between your own servicesgRPCOrder service asks the pricing service for a price
Tip: Most real apps use REST for almost everything and add one of these only where it is clearly needed. Do not rebuild a simple CRUD app in GraphQL just because it is popular.

Watch the lesson

Beyond REST: GraphQL, WebSockets and webhooks · 1/7

GraphQL WebSockets and SSE Webhooks gRPC

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)

Task 1 · Code · Javascript

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.

Task 2 · Code · Javascript

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.

Task 3 · Practice

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

Question 1

1.What is the main benefit of GraphQL for an app?

Question 2

2.A chat feature where both people send messages all the time is best built with:

Question 3

3.A webhook from a payment gateway arrives. What must your server do before trusting it?

Question 4

4.The gateway sends the same payment event twice because your first reply was slow. A correct handler:

Question 5

5.Where is gRPC mostly used?

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.

← Previous: Backend languages and frameworks