API design examples (CRUD)
easy 24 minCreate, read, update and delete cover most of what an API does with data.
See it run
Every operation message by message, and the two places where data gets lost.
Operations
Create a product
Staff adds a product to the catalogue.
Step 1 of 7
Fill in the form
Name, price, description and stock.
Step 1: Fill in the form
def create(request): require(request.user, "products:write") # 401, 403 data = validate(request.body) # 400, 422 row = db.insert("products", data) # the server makes the id return 201, row, {"Location": f"/products/{row.id}"}- Method
- POST
- Success
- 201
- Sent twice
- two products
Return the created item and its Location, so the client needs no second request.
In the real world
The same api design examples (crud) doing real jobs. Pick one and step through it.
The product was created, but the answer never arrived.
Step 1 of 4
POST
The dashboard creates a product.
Step 1: POST
Common mistakes
The bugs interviewers watch for, with the fix beside each.
PUT with some of the fields
criticalPUT means replace. Fields you leave out are lost or reset.
WrongPUT /products/1{"price": 80}RightPATCH /products/1{"price": 80}Merging the raw body
criticalA client could overwrite the id, the owner or the timestamps.
Wrongproduct.update(request.body)Rightallowed = {"name", "price", "stock"}product.update({k: v for k, v in request.body.items() if k in allowed})Verbs and singulars in URLs
minorThe method is the verb, and the collection is plural.
WrongPOST /product/createRightPOST /productsLast save wins
majorTwo editors overwrite each other without any error.
WrongUPDATE products SET stock = 45 WHERE id = 1RightUPDATE products SET stock = 45, version = 8WHERE id = 1 AND version = 7
Interview tips
How to explain it
- Two addresses, five methods.
- 201 for create, 204 for delete.
- PATCH for a part, PUT for the whole.
Memory trick
- Can Robots Update Databases?
- 2 I did it, 4 you slipped, 5 I slipped.
- PUT puts it all back.
Add in interviews
- Idempotency key on important POSTs.
- ETag and If-Match for editors.
- A limit on every list.
Be careful with
- Deleting what others point at.
- Actions that are not CRUD.
- Tables exposed as they are.