API design introduction
easy 24 minAn 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.
See it run
One request from tap to screen, what can refuse it, and how nouns become endpoints.
Operations
Search products
A shopper searches for headphones. Nine messages, there and back.
Step 1 of 9
Tap
The shopper types headphones and taps search.
Step 1: Tap
GET /products?q=headphones HTTP/1.1Authorization: Bearer fake-token-for-docsdef search(request): user = authenticate(request) # 401 if unknown allow(user, "products:read") # 403 if not allowed q = validate(request.query) # 422 if wrong rows = db.find_products(q) return 200, to_json(rows, page=1)- Round trips
- 1, when connected
- Ends with
- 200
- New connection
- 3 with TLS 1.3
Say the steps in order: receive, authenticate, authorize, validate, process, respond.
In the real world
The same api design introduction doing real jobs. Pick one and step through it.
The team replaces the database. The apps do not notice.
Step 1 of 2
Today
The app calls the API, the API reads PostgreSQL.
Step 1: Today
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A verb in every URL
minorThe method already says what to do. Verbs grow into hundreds of unrelated addresses.
WrongPOST /createNewProductPOST /deleteProductFromCatalogRightPOST /productsDELETE /products/{id}GET that changes something
criticalCrawlers, link previews and retries call GET freely. Each call would change data.
WrongGET /orders/789/cancelRightPOST /orders/789/cancellation200 with an error inside
majorCaches, gateways, dashboards and retries read the status code and believe it worked.
Wrongreturn 200, {"error": "not found"}Rightreturn 404, {"error": "product_not_found"}Trusting the address
criticalAnyone can change the id in a URL. The server must check who owns the order.
Wrongreturn db.order(order_id)Rightorder = db.order(order_id)if order.user_id != user.id: return 404, {"error": "order_not_found"}
Interview tips
How to explain it
- An API is a contract between programs.
- URL is the noun, method is the verb, status is the outcome.
- What is behind it can change.
Memory trick: WAITER
- Web-based, Application interface, Intermediary.
- Transport by HTTP methods, Endpoints define resources.
- Request and response.
In five minutes
- Three to five endpoints.
- One error per endpoint.
- Say paging and idempotency out loud.
Avoid
- Endpoints copied from tables.
- Lists without a limit.
- Sessions inside one server.