AlgoViz

API design examples (CRUD)

easy 24 min

Create, 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

Our systemStaffDashboard appAPI serverDatabaseproducts

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

Our systemStaffDashboard appAPI serverDatabaseproducts

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

    critical

    PUT means replace. Fields you leave out are lost or reset.

    Wrong
    PUT /products/1{"price": 80}
    Right
    PATCH /products/1{"price": 80}
  • Merging the raw body

    critical

    A client could overwrite the id, the owner or the timestamps.

    Wrong
    product.update(request.body)
    Right
    allowed = {"name", "price", "stock"}product.update({k: v for k, v in request.body.items() if k in allowed})
  • Verbs and singulars in URLs

    minor

    The method is the verb, and the collection is plural.

    Wrong
    POST /product/create
    Right
    POST /products
  • Last save wins

    major

    Two editors overwrite each other without any error.

    Wrong
    UPDATE products SET stock = 45 WHERE id = 1
    Right
    UPDATE 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.