API Design

What this lesson covers

An API is a documented way in which external consumers interact with code. The contract says what the code does and leaves out how. WhatsApp exposes getAdmins to find all the admins of a group. The call takes a group ID and returns a list of admin objects. The design runs through a checklist. In a microservice architecture, getAdmins belongs to the group service. The action defines the name, so an API that also returns the groups the admins belong to is no longer getAdmins. No additional parameters are taken, except information that saves the service four or five IO calls to other microservices. A response stuffed for extensibility costs network and is confusing. Defining every possible error and returning one generic error are both extremes. On an HTTP endpoint the API has a route that says where the function is, an action, and request and response objects. The route holds the address of the site, the model, the function and a version such as v1. HTTP already defines GET, so the function is named admins. A clean API has no side effects: a setAdmins that also creates the group does more than its name says. A huge response is broken into pieces. Pagination gives the client an offset: of 200 members, the first 10 and then the next 10. Perfect consistency is slow. A cached response is slightly older, and returning only the essentials under database load is service degradation.

  • An API is a contract that says what the code does for external consumers
  • The action defines the name of an API
  • Extra parameters are avoided, except to save the service IO calls to other microservices
  • An API has no side effects, and a missing group returns 404
  • Pagination and fragmentation break large responses into smaller pieces