Describe an API contract and compare resource, field, and operation-based interfaces.
Lesson goal
Specify the inputs, successful result, and error behavior a client needs, then recognize three ways to express that contract.
Before you begin — HTTP.
A weather app needs to display the temperature for a city. The team building the screen should be able to tell what to send, what units it will receive, and what to show for an unknown city. Those decisions form part of an application programming interface (API), the contract one software component exposes to another.
Suppose the weather service accepts a city identifier and returns a temperature in degrees Celsius. It also defines a response for an unknown city. The app can format a successful reading or display the documented error. The service can change how it stores observations as long as it keeps those promises.
Think through the contract in order. Input tells the caller how to identify the city. Output specifies the field, its type, and its units. Error behavior tells the caller how to distinguish an unknown city from a successful reading of zero degrees. A numeric field alone would leave the caller guessing.
A local function such as Math.max and an HTTP endpoint both have interfaces. A local library call can run inside the calling program. A request to a remote service crosses a network boundary and can time out while the service is still working.
Knowing the boundary helps a designer choose what failures the contract must describe. A valid city identifier is enough to construct a weather request. Receiving a timely reply also depends on the network and the remote service.
Suppose a client needs user 42’s name. Each of the next lessons expresses that operation with a different contract.
| Style | What the client specifies | Where to see it |
|---|---|---|
| REST | A resource URI and an HTTP method, such as GET /users/42. | REST |
| GraphQL | Fields from a typed schema, such as the name belonging to user 42. | GraphQL |
| RPC | A named operation and arguments, such as GetUser(42). | RPC |
A service can also publish events or stream updates when clients need to hear about changes as they happen. The right contract follows from what the caller needs to do.
The weather service changes its storage engine this week. Next week it keeps the same response field but starts reporting Fahrenheit. Which change affects the app?
The app can keep using the same contract after the storage change. Switching units changes the meaning of a successful response. The app would display the wrong temperature even though it could still parse the number.