Find a course

Module 5: Designing APIs and Beyond RESTLesson 12 of 1214 min

Webhooks, GraphQL and Beyond REST

Compare REST with webhooks, GraphQL, gRPC and WebSockets, understand CORS in the browser, and choose the right style for each integration problem.

Step 1 of 13Learn

When the server needs to call you: webhooks

A store wants to know the moment a customer's payment succeeds. With plain REST, the store's server would have to poll: ask GET /payments/{id} every few seconds until the status changes. Polling wastes thousands of requests and still reacts late.

Webhooks flip the direction. The store registers a URL with the payment provider, such as https://shop.example/hooks/payments. When an event happens, the provider sends an HTTP POST to that URL:

{
  "id": "evt_5521",
  "type": "payment.succeeded",
  "created": "2026-03-03T10:15:02Z",
  "data": { "paymentId": "pay_901", "amount": 4999, "currency": "usd" }
}

The store's endpoint processes it and replies 2xx quickly. If it doesn't, the provider typically retries with backoff for hours or days.

Building a reliable webhook receiver:

  • Verify the signature. Anyone can send a POST to your URL. Providers sign each delivery, often an HMAC of the body sent in a header, and you must check it with your shared secret before trusting the event.
  • Expect duplicates. Because of retries, the same event can arrive twice. Record processed event IDs and skip repeats, making the handler idempotent.
  • Respond fast, work later. Acknowledge immediately and do slow work, such as sending emails, in a background job.
  • Don't rely on order. Events can arrive out of sequence; check timestamps or fetch the latest state from the API when in doubt.

Step 2 of 13Chart

Requests needed to learn that one payment succeeded

Assume the payment completes 10 minutes after it starts. Faster polling costs more requests; slower polling means a longer delay. A webhook needs one call, sent the moment it happens.

Requests needed to learn that one payment succeededBar chart with 3 categories: Poll every 5 s: 120; Poll every 30 s: 20; Webhook: 1.0255075100125Poll every 5 sPoll every 30 sWebhook120201
Worked example: 600 seconds ÷ polling interval.
Requests needed to learn that one payment succeeded
ItemRequests
Poll every 5 s120
Poll every 30 s20
Webhook1

Step 3 of 13Practice · What would you do?

What would you do?

A webhook endpoint receives payment.succeeded events and sends the customer a receipt email for each one. Some customers report getting two identical receipts. What's the most likely cause, and the fix?

Step 4 of 13Learn

GraphQL: ask for exactly the fields you need

A mobile screen shows a user's name, their three latest orders and each order's total. With a typical REST API, that might take several requests: GET /users/7, GET /users/7/orders?limit=3, and perhaps one more per order for details. Each response also includes many fields the screen doesn't use. These problems are called under-fetching (too many round trips) and over-fetching (too much data).

GraphQL, released publicly by Facebook in 2015, takes a different approach. There's usually one endpoint, such as POST /graphql, and the client sends a query describing exactly the shape of data it wants:

query {
  user(id: 7) {
    name
    orders(last: 3) { id total }
  }
}

The response mirrors the query:

{ "data": { "user": { "name": "Ana", "orders": [ { "id": "o1", "total": 42.5 } ] } } }

The server publishes a typed schema of everything that can be queried, which enables excellent tooling and autocompletion. Changes go through mutations, and live updates through subscriptions.

Trade-offs: HTTP caching is harder because everything is a POST to one URL; one complex query can be expensive for the server, so limits are needed; and errors often come back with status 200 and an errors array, so clients must check the body. GraphQL shines when many different clients need different slices of richly connected data.

Step 5 of 13Compare

REST vs. GraphQL

AspectRESTGraphQL
EndpointsMany: one per resource or collectionUsually one, such as /graphql
Who decides the response shapeThe server, per endpointThe client, per query
Fetching related dataOften several requestsOne query can follow relationships
HTTP cachingWorks naturally with GET and cache headersHarder; usually handled by client libraries
Error signalingHTTP status codesOften 200 with an errors array in the body
Common fitPublic APIs, simple resources, caching-heavy readsApps with many screens needing different slices of connected data

Step 6 of 13Learn

gRPC, WebSockets and choosing a style

Two more styles complete the picture.

gRPC, open-sourced by Google, is popular for communication between internal services. Instead of JSON, it uses Protocol Buffers, a compact binary format defined by a schema file, and runs over HTTP/2. It's fast, strongly typed and generates client and server code in many languages. Browsers can't call it directly without a proxy, which is why it's less common for public APIs.

WebSockets keep one connection open so the server and client can both send messages at any time. They suit real-time features: chat, live sports scores, multiplayer games, collaborative editing. Server-Sent Events are a simpler one-way alternative for streaming updates from server to browser.

How to choose:

  • REST for most public and general-purpose APIs: simple, cacheable, universally understood.
  • GraphQL when diverse clients need flexible queries over connected data.
  • gRPC for high-volume, low-latency calls between your own back-end services.
  • Webhooks when another system must tell you about events as they happen.
  • WebSockets for continuous two-way, real-time communication.

Real systems mix them: a public REST API, gRPC between internal services, webhooks for partners, and WebSockets for the live dashboard.

Step 7 of 13Practice · Match the pairs

Match each requirement to the API style that fits best.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. A payment provider must notify a shop whenever a refund completes
  2. A chat app needs instant two-way messages between users and the server
  3. Twenty internal microservices exchange millions of small, typed calls per minute
  4. Web, iOS and smartwatch apps each need different fields from the same connected data
  5. A public API for listing and managing products, easy for anyone to call and cache

Step 8 of 13Diagram

Choosing an API style

Choosing an API styleHierarchy diagram: What do you need?, Client asks for data, REST, GraphQL, Server pushes events, Webhooks, WebSockets, Fast internal calls, gRPC.What do youneed?Client asksfor dataRESTGraphQLServerpusheseventsWebhooksWebSocketsFast internalcallsgRPC

Tap a shape with to see more.

What do you need?
Client asks for data
REST

Simple, cacheable resources; the default for public APIs.

GraphQL

Clients choose exact fields; good for varied screens.

Server pushes events
Webhooks

Server-to-server notifications.

WebSockets

Live, two-way connection with a browser or app.

Fast internal calls
gRPC

Binary Protocol Buffers between services.

Step 9 of 13Learn

Calling APIs from the browser: CORS

One more concept surprises nearly everyone who calls APIs from front-end JavaScript. A page at https://myapp.example runs:

fetch('https://api.other.example/data')

and the browser console shows: "blocked by CORS policy". The same request works perfectly from curl or Python. Why?

Browsers enforce the same-origin policy: a script may freely read responses only from its own origin (the combination of scheme, host and port). This stops a malicious page you visit from quietly reading your email or bank data from other sites using your cookies.

CORS (Cross-Origin Resource Sharing) is how a server opts in to sharing with other origins. It sends headers such as:

Access-Control-Allow-Origin: https://myapp.example

For requests that aren't "simple", such as those with a JSON content type or an Authorization header, the browser first sends a preflight OPTIONS request to ask permission, and only sends the real request if the server approves.

Key points: CORS is enforced by browsers, not servers, which is why curl isn't affected. It is fixed on the server by sending the right headers, not in your front-end code. If you don't control the API, call it through your own back end, which also keeps secret keys out of the browser.

Step 10 of 13Practice · Choose one

A front-end developer's fetch call to a third-party API fails with a CORS error, but the same request works from curl. What explains this?

Step 11 of 13Practice · Diagram

What the browser does for a cross-origin request

Which participant enforces CORS?

Tap the shape that answers the question, then press Check.

What the browser does for a cross-origin requestProcess diagram: Page calls fetch() → Browser sends preflight → API answers with CORS headers → Browser decides.Page callsfetch()BrowsersendspreflightAPI answerswith CORSheadersBrowserdecides
Page calls fetch()

Code from https://myapp.example asks for https://api.other.example/data.

Browser sends preflight

For non-simple requests, an OPTIONS request with an Origin header goes first.

API answers with CORS headers

For example Access-Control-Allow-Origin: https://myapp.example.

Browser decides

Origin allowed: the real request proceeds. Not allowed: the page gets a CORS error.

Step 12 of 13Practice · Code challenge

Make a webhook handler idempotent. Write createHandler() that returns a function handle(event). The first time an event with a given event.id arrives, handle returns "processed". Any later event with an ID already seen returns "duplicate".

Runs in a sandbox in your browser.
  • (() => { const h = createHandler(); return [h({ id: "evt_1" }), h({ id: "evt_2" }), h({ id: "evt_1" })]; })()
  • (() => { const h = createHandler(); h({ id: "a" }); h({ id: "a" }); return h({ id: "a" }); })()
  • (() => { const h1 = createHandler(); const h2 = createHandler(); h1({ id: "x" }); return h2({ id: "x" }); })()

Step 13 of 13Practice · True or false

A webhook receiver can trust any POST that arrives at its URL, because only the provider knows the address.