APIs with FastAPI · Chapter 16 of 26

Background tasks and webhooks

By the end of this chapter you can do slow work after the response has gone, tell merchants about changes by webhook instead of making them ask, sign every webhook so they can trust it, verify the webhooks partners send you, refuse replayed ones, and handle the same webhook arriving twice without counting it twice. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Security and real-world behaviour
  • 4 tasks
  • FastAPI
  • In the all labs plan

The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.

Why you need this

Gulabi Block Prints' shop software asks DakiyaGo about every open parcel every minute: "is DKG10027 still picked up? still? still?" Thousands of requests a day, nearly all with the same answer. Imran knows what their developer wants instead: "Call us when something changes. Here is our URL." That call is a webhook: DakiyaGo's server makes an HTTP request to the merchant's server.

It turns the API inside out. Now DakiyaGo is the client, waiting on a server it does not run, which may be slow or down. And it works in the other direction too: Rahgir, the line-haul partner, and the payments partner both send webhooks to DakiyaGo. Anyone on the internet can POST to those URLs, and partners deliver the same event more than once.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    notify.py: tell the merchant, after answering

    Make an app over /workspace/data/parcels.json (kept in memory) that reads WEBHOOK_URL from the environment (default http://127.0.0.1:9100/hooks), with PATCH /parcels/{awb}/status taking {"status": ...}, one of picked_up, in_transit, out_for_delivery, delivered or returned (422 otherwise; 404 for an unknown AWB). It changes the parcel's status, answers {"awb": ..., "status": ...} at once, and after the response POSTs {"event": "parcel.status_changed", "awb": ..., "merchant_id": ..., "status": ...} to WEBHOOK_URL. A request that failed sends no webhook.

    The check runs your app with uvicorn and points WEBHOOK_URL at a merchant server of its own that takes 1.5 seconds to answer: your PATCH must answer in under a second, and the webhook must still arrive.

  2. Task 2

    signing.py: sign what you send

    Make the same app and route as task 1, and add to every webhook the header X-DakiyaGo-Signature: t=<timestamp>,v1=<signature>. The timestamp is whole seconds since 1970 when it is sent; the signature is HMAC-SHA256, keyed with WEBHOOK_SECRET from the starter, of the timestamp, a dot, then the body's bytes, written as hex.

    The check catches your webhook and recomputes the signature from the bytes that arrived.

  3. Task 3

    incoming.py: check who is knocking

    Rahgir, the line-haul partner, sends status updates such as {"id": "evt_3K9", "awb": "DKG10004", "status": "delivered"} with the header X-Rahgir-Signature: t=<timestamp>,v1=<hex HMAC-SHA256 of the timestamp, a dot and the raw body>, keyed with RAHGIR_SECRET from the starter. Make an app over /workspace/data/parcels.json (in memory) with POST /webhooks/rahgir, which verifies the signature and only then sets the parcel's status and answers {"received": true}, and GET /parcels/{awb}, which answers the parcel.

    Answer 401 and change nothing for no header, a header that is not t=...,v1=..., a wrong signature, a body changed after signing, and a timestamp more than 5 minutes from now. The check sends a genuine webhook pretty-printed, with spaces and new lines.

  4. Task 4 · interview question

    Interview: once.py, the same webhook twice

    The payments partner sends POST /webhooks/cod with {"id": "evt_...", "awb": ..., "amount": <rupees>} when cash on delivery is collected, and retries until it gets a 2xx. Make an app where that adds amount to the balance of the parcel's merchant (parcels.json says whose it is) and answers 200; an event id already handled answers 2xx and changes nothing; an unknown AWB answers 404. GET /merchants/{merchant_id}/balance answers {"merchant_id": ..., "balance": ...}, starting at 0 for every merchant in merchants.json. Leave the signature out here.

    The check delivers one event three times, then new ones, including a new event with the same AWB and amount. The interviewer will ask what goes wrong when the same webhook arrives twice, and what the second delivery should get back.

What you will learn

  • BackgroundTasks: work that runs after the response is sent.
  • Outgoing webhooks, and why they never hold up a response.
  • Signing a webhook with HMAC-SHA256, over the exact bytes sent.
  • Verifying an incoming webhook, and replay protection.
  • Idempotent handlers: the same event twice, counted once.

More in Security and real-world behaviour

Build "Background tasks and webhooks" yourself

DakiyaGo, a Jaipur courier startup, takes bookings on WhatsApp. Merchants want an API, and you build it. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.