AlgoViz

API design introduction

easy 24 min

An API is a contract: it says what a program may ask for and what it gets back, and it hides how the work is done.

Video lesson · Chapter 1 of 5

Search the catalogue

0:00 / 2:58

What an API is

1:21Reel

Theory

Read or listen first. About 2 min.

What it is

API stands for Application Programming Interface. An application is any piece of software with its own job. Programming means that other software uses it, through code. The interface is the line between the two: what you may ask, how you ask, and what comes back.

A web API puts that line on the network. One program sends a request over HTTP, another sends a response. The caller never sees the code, the database or the language behind it. It only sees the contract.

API design is the work of choosing that contract: which things exist, what can be done to them, what can go wrong, and how all of that is written down.

Why it exists

Without an API, every app would reach into the database itself. Each one would carry the password, know the table layout, and break whenever a table changed. An API gives one guarded door with rules behind it.

A contract is also hard to take back. Once strangers have built on it, every name you chose is in their code. That is why the design deserves thought before the code does.

A short history

  1. 1991

    HTTP, as the World Wide Web software first uses it, has a one-line request: the word GET and a document address. The reply is a page of HTML.

  2. May 1996

    RFC 1945 describes HTTP/1.0, with methods, headers and status codes.

  3. January 1997

    RFC 2068 standardises HTTP/1.1, including PUT, DELETE and cache rules.

  4. 2000

    Roy Fielding, one of the HTTP authors, describes REST in a doctoral thesis: the design rules behind the web, written down as an architectural style.

  5. June 2022

    RFC 9110 gathers the meaning of methods, headers and status codes into one document shared by HTTP/1.1, HTTP/2 and HTTP/3.

Words to know

Client and server
The program that asks and the program that answers.
Endpoint
One method on one address, such as GET /products.
Resource
A thing with an address: a product, a cart, an order.
Representation
The form a resource takes in a message, for example JSON.
Stateless
Each request carries everything the server needs to understand it.
Safe
The client asks for no change. GET is safe.
Idempotent
Sending it twice is meant to have the same effect as sending it once.
Payload
The body of a request or response.

How it works

Step through the idea, or press Play.

Step 1 of 3

Name the resources. Nouns with addresses: products, carts, orders

Understand it

Start here

The waiter

Imagine a restaurant. You are hungry, but you cannot walk into the kitchen and cook. A waiter takes your order, gives it to the kitchen and brings back your meal. In software, that waiter is called an API.

Ordering at a restaurant
KITCHENSam7 pmReserved table

The kitchen can buy a new oven or hire another cook, and the menu stays the same.

Restaurant and API, side by side

RestaurantAPIMeaning
MenuDocumentationWhat you can order
OrderHTTP requestWhat you want
WaiterEndpointCarries messages both ways
KitchenServerDoes the actual work
DishHTTP responseWhat you get back
ReservationAuthenticationWho you are

The idea

Why not talk to the database directly?

Without an API

Without an API: a partner site, a web app and a phone app each send SQL and a password straight to a database that is open to the internet.
Every copy of every app holds the database password and knows the tables.

With an API

With an API: the partner site, web app and phone app send HTTP and JSON to the API contract at the edge of our system. An API server applies the rules and queries the database with SQL.
One contract at the edge. Everything inside the dashed line can change without telling the apps.

With an API

  • Secure: the API checks who is asking and what they may do.
  • Flexible: tables and code can change inside.
  • Efficient: the server runs and tunes the queries.
  • Maintainable: one place to fix a rule.

Without

  • Insecure: database credentials in every app.
  • Inflexible: apps are tied to the table layout.
  • Inefficient: complex queries written in each app.
  • Unmaintainable: change the database, change every app.

Kinds

Four kinds of API

  • Web APIs

    Called over HTTP: Stripe, Google Maps, GitHub. This topic is about these.

  • Library APIs

    Functions and classes you import: React, NumPy, jQuery.

  • Operating system APIs

    How a program asks for files, memory and windows: Windows API, POSIX, macOS.

  • Hardware APIs

    How code drives a device: graphics cards, sensors, USB.

HTTP

What HTTP gives you

  • Request and response

    The client sends a request, the server sends a response. The server does not speak first.

  • Stateless

    Each request stands alone. HTTP itself does not remember the previous one.

  • Readable model

    Methods, paths and headers are words. HTTP/1.1 sends them as text; HTTP/2 and HTTP/3 send the same words in binary frames.

  • Reliable transport

    Runs over TCP, or over QUIC for HTTP/3. Bytes arrive complete and in order, or the connection fails. It may fail after the server did the work.

Text
POST /api/v1/orders HTTP/1.1              <- method, path, protocolHost: api.shopeasy.example                <- headersContent-Type: application/jsonAuthorization: Bearer fake-token-for-docsAccept: application/json                                          <- empty line{ "product_id": "PROD-001", "quantity": 2 }   <- body (optional)
A request: request line, headers, empty line, body.
Text
HTTP/1.1 201 Created                      <- protocol, status code, status textContent-Type: application/json            <- headersLocation: /api/v1/orders/ORD-789X-RateLimit-Remaining: 99{ "order_id": "ORD-789", "status": "confirmed", "total": 159.98 }
The response. The Location header says where the new order lives. Two items at 79.99 make 159.98.

HTTP

Methods

MethodUseSafeIdempotentMemory
GETReadYesYesGet me data
POSTCreate, or run an actionNoNoPost new content
PUTReplace the whole thingNoYesPut it all back
PATCHChange a partNoNot by itselfPatch one hole
DELETERemoveNoYesDelete it
Safe and idempotent describe what the client may expect. Why that matters for retries: Idempotency.

Methods are practised one by one in API design examples.

HTTP

Status codes and headers

The first digit tells the story

FamilyMeaningCommon codes
2xxIt worked200 OK, 201 Created, 202 Accepted, 204 No Content
3xxLook elsewhere, or you already have it301, 304 Not Modified, 308
4xxThe request is the problem400, 401, 403, 404, 409, 422, 429
5xxThe server is the problem500, 502, 503, 504
What to put in an error body is a topic of its own: API error handling.

Headers you meet every day

HeaderDirectionPurpose
HostRequestDomain name of the server
Content-TypeBothFormat of the body, such as JSON or XML
AuthorizationRequestCredentials: a token or a key
AcceptRequestFormat wanted in the response
User-AgentRequestWhich client program is calling
LocationResponseURL of the created resource, with 201
Cache-ControlResponseMay it be stored, and for how long
X-RateLimit-*ResponseQuota left (a custom name, not a standard)
Retry-AfterResponseWhen to try again, with 429 or 503

REST

REST and its six constraints

REST means REpresentational State Transfer. It is an architectural style, not a protocol: a set of constraints that make web systems scale and evolve. Most APIs called REST follow some of them, usually not all.

  1. 1

    Client and server are separate

    The user interface and the data live apart and can change apart. Example: a phone app and an API server.

  2. 2

    Stateless

    Each request holds all the information needed. Example: the token travels with every request.

  3. 3

    Cacheable

    Responses say whether they may be stored. Example: Cache-Control: max-age=3600. See API caching.

  4. 4

    Uniform interface

    Resources have addresses, methods mean the same everywhere, messages describe themselves and may link to the next step. Example: GET /products, POST /orders.

  5. 5

    Layered system

    The client cannot tell whether it talks to the server or to something in between. Example: client, gateway, server, database.

  6. 6

    Code on demand

    The server may send code to run. Example: JavaScript for a browser. This is the only optional one.

Why statelessness helps scaling

Any server can answer any request, because nothing about the client is kept inside one server.

Design

Think in nouns

REST thinks in resources (nouns), not actions (verbs). The method is the verb, the URL is the noun.

AvoidPreferWhy
/getAllProductsGET /productsGET already says get
/createNewProductPOST /productsPOST to a collection creates an item
/updateProductByIdPUT /products/{id}PUT on one address replaces it
/deleteProductFromCatalogDELETE /products/{id}DELETE removes it

Resources of a shop

ResourceWhat it is
/productsThe catalogue
/products/{id}One product
/categoriesProduct categories
/usersUser accounts
/users/{id}/cartOne user's cart
/users/{id}/ordersOne user's order history
/ordersAll orders, for staff only
/orders/{id}One order
The address never grants access. The server must check that this caller may see this order: API authorization.

From a requirement to an endpoint

Process

One request, from tap to screen

A shopper types "wireless headphones" and taps search. A moment later, 47 matching products appear, 20 of them on the first page.

  1. 1

    User action

    The shopper taps the search button in the app.

  2. 2

    Request formation

    The app builds method, URL, headers and body: GET /api/v1/products?search=wireless%20headphones&limit=20. The space becomes %20.

  3. 3

    Network transit

    DNS lookup, TCP connection, TLS handshake. A connection that is already open skips all three.

  4. 4

    Server processing

    The server authenticates, authorizes, validates and queries the database.

  5. 5

    Response formation

    Rows become JSON, headers are added, the response is sent.

  6. 6

    UI rendered

    The app parses the JSON and draws the product cards.

Search products

Some systems check the token in the gateway, some in the server. What a user may see is checked by the server that owns the data.

Inside the server

Cheap checks first. A bad token costs nothing but the check.
Text
GET /api/v1/products?search=wireless%20headphones&limit=20 HTTP/1.1Host: api.shopeasy.exampleAuthorization: Bearer fake-token-for-docsAccept: application/jsonX-Device-ID: ios-exampleHTTP/1.1 200 OKContent-Type: application/jsonX-Response-Time: 45ms{  "data": [    { "id": "PROD-001", "name": "Wireless Headphones", "price": 149.99, "rating": 4.8 }  ],  "pagination": { "total": 47, "page": 1, "has_more": true }}
The full exchange. The list is shortened to one item here; a real first page holds 20.

Where the time goes

Tnew=RTT⏟TCP+RTT⏟TLS 1.3+RTT⏟request+Tserver=3×100+45=345 msT_{\text{new}} = \underbrace{RTT}_{\text{TCP}} + \underbrace{RTT}_{\text{TLS 1.3}} + \underbrace{RTT}_{\text{request}} + T_{\text{server}} = 3 \times 100 + 45 = 345\text{ ms}
Assumptions: a 100 ms round trip on mobile, 45 ms of server work, DNS already known. With an open connection: 100+45=145100 + 45 = 145 ms. Round trips cost more than the server here.

Traffic for one endpoint

1,000,00086,400≈12/s,×3≈35/s at peak,35×8 KB=280 KB/s\frac{1{,}000{,}000}{86{,}400} \approx 12/\text{s}, \quad \times 3 \approx 35/\text{s at peak}, \quad 35 \times 8\text{ KB} = 280\text{ KB/s}
Assumptions: one million searches a day, peak three times the average, 8 KB per response. One server handles this. The contract needs more care than the capacity.

Two more flows

A write, and a refusal

Create an order

StepActionResult
1POST /ordersThe app asks for an order
2Check the cartEvery item is in stock
3Process the paymentThe payment provider confirms the charge
4Create the recordINSERT INTO orders
5201 CreatedConfirmation and a Location header
If the connection drops after step 3, the app cannot know whether it paid. A client-made key makes the retry safe: Idempotency.

No token: 401

401 means we do not know who you are. 403 means we know, and the answer is no. See API authentication.

Trade-offs

REST: good and bad

Strengths

  • Simple to understand and to try
  • Uses HTTP caching as it is
  • Stateless, so easy to scale out
  • Tools and frameworks everywhere
  • Readable URLs and payloads

Weak spots

  • Over-fetching: more data than the screen needs
  • Under-fetching: several requests for one screen
  • No built-in push from the server
  • Versioning needs a plan
  • No single error format that everybody uses

Other styles answer some of these: REST, GraphQL and gRPC. Changing a published API: API versioning. For error bodies there is now a standard, RFC 9457, that you can choose to follow.

Checklist

Seven questions for any endpoint

  1. 1

    Who calls it?

    Our app, partners, the public? Strangers need more stability.

  2. 2

    Which resource?

    One noun, one address.

  3. 3

    Which method?

    Safe? Can it be repeated?

  4. 4

    What goes in and out?

    Required fields, types, limits, examples.

  5. 5

    What can go wrong?

    One status and one error code per case.

  6. 6

    How much can it return?

    Never an endless list: API pagination.

  7. 7

    How often may it be called?

    Rate limiting.

Summary

The whole topic in one minute.

An API is the contract between programs. It hides the kitchen: callers see the menu, send an order and receive a dish, while storage, code and servers can change behind it.

With HTTP, the URL names a resource, the method says what to do, the headers describe the message and the status code says how it ended. REST adds design rules, above all statelessness and a uniform interface. Design the resources first, then methods, then errors, then limits, and treat everything you publish as a promise.

  • API means Application Programming Interface: the waiter between client and server.
  • REST uses resources (nouns) and HTTP methods (verbs).
  • HTTP is stateless: each request stands alone.
  • 2xx success, 4xx the request, 5xx the server.
  • GET reads, POST creates; the Authorization header carries credentials.
  • A published contract is a promise. Design it before the code.

Sources