APIs and REST

Topic 5 of 9 in Week 1: Foundations and the interview framework11 min readBeginnerFree course

Overview

Every system you design has an API: the contract between clients and your servers, or between your own services. In interviews, writing down the API early is one of the fastest ways to make a vague problem concrete. This lesson covers how to design clean HTTP APIs in the REST style, and briefly how the alternatives differ.

Anatomy of a REST call

A REST request and response. The request is POST /v1/orders with a Host header, an Authorization bearer token, a JSON content type, an Idempotency-Key header and a JSON body listing items with sku A1 and quantity 2. The response is 201 Created with a Location header pointing to /v1/orders/981 and a JSON body with id 981 and status pending. A table of methods: GET reads, POST creates, PUT or PATCH replace or update, DELETE removes. A table of status codes: 2xx success such as 200, 201 and 204; 3xx redirect such as 301 and 304; 4xx client error such as 400, 401, 404 and 429; 5xx server error such as 500, 502 and 503. For 4xx, fix the request rather than retrying; for 5xx and 429, try again later with backoff.

A request has four parts:

  • a method that says what to do,
  • a path that names the resource,
  • headers with metadata such as authentication and content type,
  • an optional body, usually JSON.

The response carries a status code, headers and usually a body.

Resources and methods

REST (representational state transfer) models an API as resources, the nouns of your domain, each with a URL:

Text
/v1/users/17
/v1/users/17/orders
/v1/orders/981

HTTP methods are the verbs:

Method Meaning Safe? Idempotent?
GET Read a resource or a list Yes Yes
POST Create a resource, or trigger an action No No
PUT Replace a resource entirely No Yes
PATCH Change some fields No Usually not guaranteed
DELETE Remove a resource No Yes

Good habits:

  • Use nouns in paths and let the method be the verb: POST /orders, not POST /createOrder.
  • Nest only for clear ownership: /users/17/orders reads well; four levels deep does not.
  • Take the current user from the auth token, not from the URL, so one user can’t read another user’s data by editing a number.

Idempotency: making retries safe

An operation is idempotent if doing it twice has the same effect as doing it once. DELETE /orders/981 is idempotent: after the first call the order is gone, and the second call changes nothing.

POST /orders is not. Imagine a phone on a bad connection: it sends the order, the server creates it, but the response is lost. The app retries, and now the customer has two orders and is charged twice.

The standard fix is an idempotency key: the client generates a unique ID for each logical action and sends it in a header. The server stores the key with the result; if the same key arrives again, it returns the stored result instead of doing the work again. Payment APIs rely on this, and you’ll use it in the payment case study.

Status codes

Status codes tell the client what to do next:

  • 2xx, success. 200 OK, 201 Created (with a Location header), 204 No Content.
  • 4xx, the client’s fault. 400 bad input, 401 not signed in, 403 not allowed, 404 not found, 409 conflict, 429 too many requests. Retrying the same request won’t help, except for 429.
  • 5xx, the server’s fault. 500 bug, 502/504 a server behind the gateway failed or timed out, 503 overloaded or down for maintenance. Retrying later, with backoff, may succeed.

Pagination

Never return an unbounded list. There are two common styles:

  • Offset pagination: GET /posts?limit=20&offset=40. Simple and allows jumping to page 7, but slow for large offsets (the database still walks past the skipped rows), and items shift if new ones are added while the user scrolls.
  • Cursor pagination: GET /posts?limit=20&cursor=eyJpZCI6.... The cursor encodes where the last page ended (for example the last item’s timestamp and ID). It stays fast and stable on huge, changing lists such as feeds, at the cost of not jumping to arbitrary pages.

For feeds, timelines and anything large, choose cursors.

Versioning and evolution

Clients, especially mobile apps, can’t all update at once, so a public API must keep working for old clients.

  • Add fields freely; clients should ignore fields they don’t know.
  • Never remove or rename a field, or change its meaning, in place.
  • For breaking changes, release a new version (/v2/... or a version header) and keep the old one running until clients have moved.

REST, GraphQL and gRPC

REST is the default for public APIs, but you should know the alternatives:

  • GraphQL: clients ask for exactly the fields they need in one request. Great for apps with many screens needing different data; harder to cache and to protect from expensive queries.
  • gRPC: compact binary messages over HTTP/2 with a strict schema. Fast and well suited to service-to-service calls inside your system; less convenient for browsers.

Week 5 compares these in more detail. In interviews, REST-style endpoints are almost always fine for the client API.

Writing the API in an interview

After clarifying requirements, list the core endpoints in a few lines, for example for a URL shortener:

Text
POST /v1/urls          {"long_url": "...", "alias": "optional"}  -> 201 {"short_url": "..."}
GET  /{code}           -> 301/302 redirect to the long URL

This takes two minutes, makes the scope concrete and drives your data model.

Recap

A good HTTP API names resources with nouns, uses methods for actions, returns meaningful status codes, paginates every list, evolves without breaking clients and makes retries safe with idempotency. Sketching the API early in an interview turns a vague prompt into something you can design against.

Exercise

Design a small API

Design the REST API for a simple to-do app where users have lists and each list has items. Users must be able to create a list, see all their lists, add an item, mark an item done, delete an item, and see a list's items 20 at a time. For each endpoint give the method, path, a short request body (if any) and the success status code.

Text
Create a list:
Get my lists:
Add an item:
Mark an item done:
Delete an item:
Get items in a list (paginated):

Summary

  • REST models the API as resources (nouns in the URL) acted on by HTTP methods (GET, POST, PUT, PATCH, DELETE).
  • GET, PUT and DELETE are idempotent; POST is not, so use an idempotency key when retries could create duplicates.
  • Status codes tell the client what to do next: 2xx success, 4xx fix the request, 5xx and 429 retry later.
  • Prefer cursor pagination over offsets for large or changing lists.
  • Version public APIs (for example /v1/) and evolve them without breaking existing clients.