Card 01/ 10

ConceptDifficulty: Beginner2 min

The API Contract: What Both Sides Agree On

A contract lists every field, type, rule and error, so client and server can be built apart and still fit.

An API contract is the full, written description of what a client may send and what the server will send back: every path and method, every field with its type and whether it is required, the formats of values, the errors, and how to authenticate. Anything the contract leaves out becomes a guess, and a guess made differently on each side is a bug found only when they meet.

An electrical socket standard works the same way: anyone can build a plug that fits, without meeting the people who wired the house. The comparison breaks because a socket standard almost never changes, while an API contract must change as the product does, and changing it without breaking clients has its own topic later in this subject.

What a contract specifies, with an example from an orders API
PartExample
Path and methodPOST /orders
AuthenticationA bearer token in the Authorization header
Request fields and typesitems, an array of objects with sku, a string, and quantity, an integer
Required or optionalitems is required; note is optional
Formats and rulesquantity between 1 and 99; deliverOn a date in the future
Success response201, with the order and a Location header
Error responses400 for malformed JSON, 422 for an invalid value, 401 without a token

What a contract does not specify. The database tables, the programming language and the internal services are the server's own business. If they appear in the contract, they cannot change without breaking clients.

Types are more than JSON types. JSON has strings, numbers, booleans, arrays, objects and null. A contract narrows them: this string is an email, this number an integer from 1 to 99, this string one of open, paid or shipped. A fixed list of allowed values like that is called an enum.

The contract is the API. The code behind it is one implementation. Two servers that keep the same contract are the same API to a client, and one server that changes a field name without notice is a different API.

So write down every field a client sends or reads, and treat what is not written down as not yet decided.

← → move through sections and cards