A finished program is a closed black box: you do not look inside, but you can ask it to do something from outside. For that it has an API, an agreement on which requests the program accepts, what it replies and in what form. Programs use each other through APIs: a browser uses the operating system’s facilities, a mobile app uses an online shop’s server, one microservice uses its neighbour.
Kinds of API
| Kind | Example |
|---|---|
| System | operating system calls: files, processes, network, such as open on Linux |
| Library | library functions that code calls directly within its own program |
| Network | requests exchanged between machines over a protocol: REST over HTTP, gRPC, WebSocket |
| Browser API | browser capabilities exposed to a page: geolocation, camera (getUserMedia), notifications |
Whatever an API connects, the contract describes the same things. The NIST glossary defines an API as an access point in a system or a library function that has a clearly defined syntax and is accessible from application programs. A contract usually fixes:
- which operations are available and how to call them: methods and functions, their parameters and types;
- the form in which data comes and goes: message formats, error codes and bodies;
- the rules for the contract’s lifetime: the API version, limits, and what counts as backward compatibility.
API and implementation
Internally, a program can change however it likes between versions as long as the contract holds: code written against the API keeps working. That is why, for a network API, the description is a separate artefact: OpenAPI schemas, .proto files for gRPC. The same agreement is used to check integration: contract tests compare a service’s actual behaviour with what it promised.
import httpx resp = httpx.get("https://api.example.com/v1/users/42", headers={"Authorization": "Bearer <token>"})if resp.status_code == 200: user = resp.json() # {"id": 42, "name": "Aziza"}The code above knows only the address and the response format. It does not need to know where the service gets its data, what language it is written in or how it is built. That is why a Python service can serve clients written in Swift, Go and JavaScript: there is one contract and any number of implementations.
Sources
the term is written from these pagesVerified 9 Nov