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.1 What is an API contract?
3 min read+10 XP
Designing APIs
At the machine: The buttons and labels are a promise. Press B4, pay ₹40, get water. The station can swap the machine's insides, but if B4 suddenly gave you a cola, or cost ₹60 without a new label, people would be furious.
In the system: An API contract is the agreement between a service and its clients about:
- What you can ask for: endpoints or operations (
GET /orders/881,POST /charges). - What you send: fields, types, which are required, limits (
amountin paise, integer, at least 100). - What you get back: response fields and their meaning, and error formats.
- Behaviour: is it safe to retry? How fast? What rate limits apply?
Good practice:
- Write it down in a machine-readable spec: OpenAPI for REST,
.protofiles for gRPC, a schema for GraphQL. Generate docs, client libraries and tests from it. - Design from the client's needs, not your database tables:
GET /orders/881should return what the order screen needs, not your internal join. - Be precise about units and formats: money as integers in the smallest unit (paise), times in ISO 8601 with time zones, IDs as strings.
- Be strict in what you send, tolerant in what you accept: clients should ignore unknown fields, so you can add new ones later (24.3).
A contract matters most for public and cross-team APIs, where you can't change every caller at once.
Memory code: "The label is a promise: same button, same result."