Lesson 2 of 17
24. 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 (amount in 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, .proto files 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/881 should 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."