24. APIs and Idempotency
1
The picture to keep in your head2
24.1 What is an API contract?3
24.2 What are the main API styles?4
24.3 How do you version an API?5
24.4 How does pagination work (offset vs cursor)?6
24.5 How should errors and status codes work?7
24.6 How does API auth work, in one page?8
24.7 What is the double-charge problem?9
24.8 How do idempotency keys work?10
24.9 How do you retry safely?11
24.10 How do webhooks work?12
Memory card and where the analogy breaks13
Practice: five levels14
Interview questions15
Solutions16
Sources17
Code lab24. APIs and Idempotency
24.6 How does API auth work, in one page?
3 min read+10 XP
At the machine: Customers pay with their own card. The vendor who restocks the machine uses a staff key. Lose your card, and you cancel it; you don't change every lock in the station.
In the system: Two questions: who is calling (authentication) and what are they allowed to do (authorisation).
API keys identify a program (a partner's server, a script):
- A long random secret sent in a header:
Authorization: Bearer sk_live_.... - Store only a hash of the key, like a password, and compare in constant time. In the chapter's code, keys are stored as SHA-256 hashes and checked with
hmac.compare_digest. - Give keys prefixes (
sk_live_,sk_test_) so leaked ones are easy to spot, scopes (read-only vs full), and make them easy to rotate and revoke. - Server-to-server only: never ship a secret key inside a mobile app or web page.
Tokens identify a user (or a user acting through an app):
- The user logs in; the auth server issues a short-lived access token, often a signed JWT carrying the user ID, scopes and expiry, plus a longer-lived refresh token.
- Each request carries
Authorization: Bearer <access token>; the API checks the signature and expiry without a database lookup. - OAuth 2.0 is the standard for letting a third-party app act for a user with limited permissions ("this app can read your orders, not pay").
Always:
- HTTPS everywhere; credentials over plain HTTP are stolen credentials.
- Authorise every request against the specific resource: user 7 may read order 881 only if it's theirs. Missing this check is one of the most common API security bugs.
- Combine with rate limits per key or user (Chapter 25).
Memory code: "Keys for programs, tokens for people, and check every door, not just the front gate."