Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

API
APIs: REST & GraphQL
0/11 completed
Beginner
What is an API?HTTP methods, status codes and headersJSON
Intermediate
REST design principlesErrors and validationPagination, filtering and sortingGraphQL basics
Advanced
Versioning and cachingRate limiting and idempotencyOpenAPI documentation
Pro
Webhooks, real-time APIs and API security
Tracks / APIs: REST & GraphQL / Pro

Webhooks, real-time APIs and API security

So far the client has always asked and the server answered. Real systems also need the opposite: the server telling you that something happened (a payment succeeded, a build finished, a message arrived). This lesson covers webhooks, real-time connections, and the security practices every production API needs.

Webhooks

With a webhook, you give the provider a URL, and it sends an HTTP POST there whenever an event happens:

Stripe ──POST https://myshop.example/webhooks/stripe──▶ your server
         { "type": "payment_intent.succeeded", "data": { … } }

This beats polling ("any news? any news?" every few seconds), which wastes requests and still reacts late.

Verifying the signature

Your webhook URL is public, so anyone could POST a fake "payment succeeded" event to it. Providers therefore sign each delivery: they compute an HMAC of the exact request body with a secret only you and they know, and send it in a header. You recompute it and compare:

Node.js · editable

Key points:

  • Verify against the raw body; re-serialised JSON may differ by a single space and break the signature.
  • Compare with crypto.timingSafeEqual, not ===, so attackers can't learn the signature byte by byte from response timings.
  • Include a timestamp in the signed data and reject old deliveries (replay protection).

Handling webhooks reliably

Providers retry failed deliveries (often for days) and may deliver an event twice or out of order. So:

  1. Respond with 2xx fast: save the event and process it in a background job; don't make the provider wait.
  2. Deduplicate by event ID: store processed IDs and skip repeats.
  3. Don't trust the order: an "updated" event may arrive before "created". When in doubt, fetch the current state from the provider's API.

Real-time APIs

Technique How it works Good for
Polling Client asks every N seconds Simple, infrequent updates
Long polling Server holds the request open until there's news Legacy fallback
Server-Sent Events (SSE) One long HTTP response that the server keeps writing events to; one-way, auto-reconnects Notifications, live feeds, streaming AI responses
WebSockets A persistent two-way connection Chat, multiplayer games, collaborative editing

SSE is plain HTTP, which makes it simple to add. The server writes data: lines and keeps the response open:

js
app.get('/events', (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
  });
  const timer = setInterval(() => {
    res.write(`event: price\ndata: ${JSON.stringify({ symbol: 'ACME', price: 101.5 })}\n\n`);
  }, 1000);
  req.on('close', () => clearInterval(timer));          // the client went away
});
js
// In the browser
const source = new EventSource('/events');
source.addEventListener('price', (e) => console.log(JSON.parse(e.data)));

WebSockets start as an HTTP request that's "upgraded" to a two-way channel. In Node, use the ws package or Socket.IO (which adds rooms, reconnection and fallbacks). Scaling them across many servers needs a shared message bus such as Redis pub/sub, because each connection lives on one server.

API security checklist

The OWASP API Security Top 10 lists the most common API weaknesses. The big ones, as checks:

Risk Protection
Broken object-level authorization: GET /orders/502 returns someone else's order Check on every request that the object belongs to (or is visible to) the caller
Broken authentication Standard, well-tested auth (OAuth 2.0 / OIDC, proven libraries); rate-limited login; short-lived tokens
Broken property-level authorization: clients can read or set fields they shouldn't (role, price) Explicit allow-lists for input fields and output fields
Unrestricted resource consumption Rate limits, page-size caps, request-size limits, timeouts
Broken function-level authorization: customers can call admin endpoints Role checks on every privileged route, denied by default
Server-side request forgery (SSRF): your server fetches a URL the attacker chose Validate and allow-list outbound URLs; block internal addresses
Security misconfiguration HTTPS only, strict CORS, security headers, no verbose errors, patched dependencies
Improper inventory Know every API and version you run; retire old ones

Plus the basics from earlier lessons: validate all input, use parameterised queries, never put secrets in URLs (they end up in logs), and log authentication failures.

API keys

Simple APIs (and server-to-server calls) often authenticate with an API key in a header:

http
GET /v1/forecast?city=Mumbai
Authorization: Bearer sk_live_51H...

Store only a hash of each key (like a password), show the key to the user once, let them create several and revoke them, and give them prefixes (sk_live_, sk_test_) so leaked keys are easy to recognise and scan for.

🎓 APIs track complete!

You've learned what APIs are, HTTP methods, status codes and headers, JSON, REST design, errors and validation, pagination and filtering, GraphQL, versioning and caching, rate limiting and idempotency, OpenAPI, webhooks, real-time APIs and API security.

Capstone project: an event-ticketing API

Design and build it, documentation first:

  1. Write the OpenAPI document for events, ticket-types, orders and attendees.
  2. Implement it (Express, FastAPI or Spring Boot) with cursor pagination and filters (/events?city=Pune&from=2026-12-01), Problem Details errors and Zod or Pydantic validation.
  3. POST /orders must be idempotent (Idempotency-Key) and must never oversell (a database transaction).
  4. Add ETags to event pages and rate limits to search and checkout.
  5. Send a signed webhook to a configurable URL when an order is paid, with retries and backoff.
  6. Add a GraphQL endpoint that lets a frontend fetch an event with its ticket types and remaining capacity in one query.
  7. Generate a TypeScript client from your OpenAPI file and use it in a small script.
✎ Check your understanding

1.Why must webhook signatures be checked against the raw request body?

2.A provider may deliver the same webhook twice. What should your handler do?

3.Which technique is a one-way, plain-HTTP stream of events from server to client?

← OpenAPI documentation