AlgoViz

API design examples (CRUD)

easy 24 min

Create, read, update and delete cover most of what an API does with data.

Video lesson · Chapter 1 of 6

Create one product

0:00 / 3:37

CRUD in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

CRUD stands for create, read, update and delete: the four things you can do with stored data. A shop adds a product, shows it, changes its price and removes it. A chat app does the same with messages, a bank with standing orders.

In a resource API, each of the four becomes an HTTP method on an address. The collection /products is the whole set, the item /products/{id} is one member. Two addresses and five methods cover the life of a product.

Why it exists

The pattern is predictable. A developer who has seen one resource can guess the next one, and tools can be generated from it.

The details decide whether it is safe. What happens when a create is sent twice? When a field is left out of an update? When two people edit the same thing? CRUD looks trivial until these questions arrive, and they arrive in every interview.

A short history

  1. 1983

    James Martin's book Managing the Data-base Environment is usually credited with making the term CRUD popular.

  2. January 1997

    RFC 2068, HTTP/1.1, defines PUT and DELETE next to GET and POST.

  3. March 2010

    RFC 5789 adds PATCH, because PUT could only replace a whole resource.

  4. April 2013

    RFC 6902, JSON Patch, describes a change as a list of operations.

  5. October 2014

    RFC 7396, JSON Merge Patch, describes a change as a partial document where null removes a field.

Words to know

Collection
The set of all items of one kind: /products.
Item
One member of it: /products/PROD-001.
Partial update
Changing some fields and leaving the rest.
Idempotent
Repeating it has the same intended effect as doing it once.
ETag
A label for one state of a resource, used to notice that it changed.
Soft delete
Marking a row as deleted instead of removing it.
Lost update
Two people edit the same thing and one change disappears.

How it works

Step through the idea, or press Play.

Step 1 of 3

Two addresses. The collection /products and the item /products/{id}

Understand it

Start here

A box of recipe cards

Imagine a box of recipe cards in a kitchen. Everything you can do with a card has a name, and the same names work for products, users and orders.

Five things you can do with a card
123RECIPESPancakes3Flour 200 gMilk 300 mlEggs 2Create

Five actions on one card. The box is the collection, the number is the id.

The idea

Four operations, one table

CRUDHTTPSQLIn a shop
CreatePOST /productsINSERTAdd a product to the catalogue
ReadGET /products, GET /products/{id}SELECTSee the list or one product
UpdatePATCH or PUT /products/{id}UPDATEChange the price
DeleteDELETE /products/{id}DELETERemove a discontinued product
The match with SQL is a memory aid. The API should show resources, not tables.

The shop behind the examples

Shoppers send GET and the staff dashboard sends POST, PATCH, PUT and DELETE to the Products API. The API reads from a cache first and uses SQL on the products database.
Shoppers read, staff write. Same resources, different permissions.

Create

POST: add a product

Text
POST /api/v1/products HTTP/1.1Host: api.shopeasy.exampleContent-Type: application/jsonAuthorization: Bearer fake-staff-token{ "name": "Bluetooth Speaker", "price": 79.99, "category": "electronics",  "description": "Portable wireless speaker", "stock": 100 }HTTP/1.1 201 CreatedLocation: /api/v1/products/PROD-003Content-Type: application/json{ "id": "PROD-003", "name": "Bluetooth Speaker", "price": 79.99,  "category": "electronics", "description": "Portable wireless speaker",  "stock": 100, "created_at": "2024-01-15T10:30:00Z" }
  • POST to the collection creates a new item.
  • 201 Created means it exists now.
  • Location is the address of the new item.
  • The server chooses the id and the timestamp. Ignore or refuse an id sent by the client.

Create, message by message

Read

GET: a list and one item

Text
GET /api/v1/products?category=electronics&limit=10200 OK{ "data": [    { "id": "PROD-001", "name": "Wireless Headphones", "price": 149.99 },    { "id": "PROD-002", "name": "USB Cable", "price": 9.99 },    { "id": "PROD-003", "name": "Bluetooth Speaker", "price": 79.99 } ],  "pagination": { "next_cursor": null } }GET /api/v1/products/PROD-001200 OK{ "id": "PROD-001", "name": "Wireless Headphones", "price": 149.99,  "description": "Noise-cancelling, 30 hours",  "review_count": 128, "related_ids": ["PROD-002"] }
Wrap a list in an object so you can add paging later without breaking anyone.
  • GET reads and 200 OK carries the data.
  • GET is safe: the client asks for no change.
  • GET is idempotent: repeating it is fine, although the data may have changed meanwhile.
  • Every list has a limit: API pagination. Filters: search and filtering.

Read through a cache

The next reader within five minutes skips the database. Details: API caching.

Update

PATCH and PUT

Staff lowers the price of the headphones from 149.99 to 129.99 for a sale.

Text
PATCH /api/v1/products/PROD-001Content-Type: application/merge-patch+json{ "price": 129.99 }            <- only what changes; the rest staysPUT /api/v1/products/PROD-001Content-Type: application/json{ "name": "Wireless Headphones", "price": 129.99, "category": "electronics",  "description": "Noise-cancelling, 30 hours", "stock": 50 }   <- everything

The same product, two updates

FieldBeforeAfter PATCH with price 80After PUT with name and price 80
nameHeadphonesHeadphonesHeadphones
price1008080
stock5050gone, or its default
categoryelectronicselectronicsgone, or its default
A strict server refuses the incomplete PUT with 400 or 422. That is kinder than losing data.

PATCH

  • Changes one field or a few
  • Small payloads
  • Less risk of losing data
  • But: not idempotent by itself, more merging logic, several formats to choose from

PUT

  • Replaces the whole resource
  • Idempotent by definition
  • Fits a form with every field
  • But: all fields needed, larger payload, a forgotten field is lost

PUT or PATCH?

Two ways to write a patch

JSON Merge PatchJSON Patch
StandardRFC 7396RFC 6902
Body{"price": 80, "badge": null}[{"op": "replace", "path": "/price", "value": 80}]
Remove a fieldSend nullremove operation
ArraysReplaced as a wholeSingle elements
Good forMost APIsPrecise or conditional changes
Merge Patch cannot store a null, because null means remove.

Delete

DELETE: remove a product

Text
DELETE /api/v1/products/PROD-OLDAuthorization: Bearer fake-staff-token204 No Content                 <- first time, empty body404 Not Found                  <- second time{ "error": "product_not_found" }
  • DELETE is idempotent: after one call or five, the product is gone. The status code may differ.
  • 204 means success with nothing to return.
  • 404 means it does not exist: already deleted, or never there. Some APIs answer 204 again, which is simpler for retries. Pick one and write it down.
  • A soft delete marks the row as deleted, so orders that mention it still work and mistakes can be undone. Personal data may have to be erased for real.

Delete, message by message

Names

Seven rules for URLs

RuleAvoidPreferWhy
1. Nouns, not verbs/getProducts, /createOrder, /deleteUserGET /products, POST /orders, DELETE /users/{id}The method is the action
2. Plurals/product/123, /user/456/products/123, /users/456Collection and item share a path
3. Hyphens/orderItems, /user_profiles, /ProductCategories/order-items, /user-profiles, /product-categoriesReadable
4. Lowercase/Products, /API/V1/PRODUCTS/products, /api/v1/productsPaths are case-sensitive
5. Nest 2 to 3 levels/users/123/orders/456/items/789/variants/users/{id}/orders, /orders/{id}/items, /products/{id}/reviewsDeep paths are fragile
6. No trailing slash/products//productsOne address per thing
7. No file extension/products.json/products with AcceptFormat is a header
Rules 2, 3, 6 and 7 are conventions. Consistency inside one API matters more than the exact choice.

Good and bad design

AvoidPreferWhy
/getAllProductsGET /productsNo verb needed
/getProductById?id=123GET /products/123An id belongs in the path
/createProductPOST /productsPOST to a collection creates
/updateProductStockPATCH /products/123Partial update
/searchProducts?q=phoneGET /products?q=phoneSearch filters a collection
/sendEmailToUserPOST /users/123/emailsThe email is the resource

Outcomes

Status codes for CRUD

  • 2xx: it worked

    200 for GET, PUT and PATCH. 201 for a create. 204 for a delete, or any success without a body.

  • 4xx: the request

    400 malformed, 401 not logged in, 403 not allowed, 404 not found, 409 conflict, 412 version check failed, 422 invalid values, 429 too many.

  • 5xx: the server

    500 internal error, 502 bad gateway, 503 unavailable, 504 gateway timeout.

Which code?

ScenarioCode
List of products200
New order created201
Item removed from the cart204
Field "name" is missing400 (some APIs use 422)
Checkout without login401
A customer tries to delete a product403
An order that does not exist404
Register with an email that exists409
Quantity is minus 2422
Quantity is larger than the stock409 (some use 422)
Too many searches429
Unexpected exception500
Database down, or overloaded on a sale day503
The difference between 400 and 422 is a convention. Choose one rule and apply it everywhere. More in API error handling.

Deep dive

Two people, one product

Two staff members open the same product. Both see a stock of 50. One sells 10 and saves 40. The other sells 5 and saves 45. The last save wins, and ten sales disappear. This is a lost update.

ETag and If-Match

The server compares the label before it writes, in one atomic step. For counters, an action such as POST /products/1/stock-movements with -5 avoids the race.

Numbers

What the choices cost

Payload of an update

PUT: 2 KB×10,000=20 MBPATCH: 50 B×10,000=0.5 MB\text{PUT: } 2\text{ KB} \times 10{,}000 = 20\text{ MB} \qquad \text{PATCH: } 50\text{ B} \times 10{,}000 = 0.5\text{ MB}
Assumption: 10,000 price updates of a 2 KB product. Small either way. The stronger reason for PATCH is that it cannot erase other fields.

Reads and writes of a shop

10,000,00086,400≈116/s,;×3≈350/s reads10,00086,400≈0.12/s writes\frac{10{,}000{,}000}{86{,}400} \approx 116/\text{s}, ; \times 3 \approx 350/\text{s reads} \qquad \frac{10{,}000}{86{,}400} \approx 0.12/\text{s writes}
Assumptions: ten million product views and ten thousand product edits a day. A thousand reads per write is why reads get the cache.

Limits

When CRUD is not enough

  • Actions with rules. Cancelling an order is not deleting it. Model it: POST /orders/{id}/cancellation.
  • Bulk work. Changing 5,000 prices one by one is slow. Offer POST /price-imports and answer 202 with a job to look at.
  • History. A bank adds entries, it does not update balances.
  • Reports. A monthly summary is its own read resource.

Summary

The whole topic in one minute.

CRUD maps to HTTP in one line each: POST a collection to create, GET to read, PATCH an item to change a part, PUT an item to replace it, DELETE an item to remove it. The URL stays a plural noun.

The hard parts are outside that line. Answer 201 with a Location, 204 without a body and the right 4xx. Remember that PUT loses what you leave out, that a repeated POST creates twice, and that two editors overwrite each other unless you use a version check.

  • Create POST, read GET, update PUT or PATCH, delete DELETE.
  • PUT replaces everything, PATCH changes what you send.
  • Plural nouns: /products, not /product. No verbs: the method is the verb.
  • 201 created, 200 fine, 204 done without a body.
  • 4xx is the request, 5xx is the server.
  • Plan for the second POST and the second editor.

Sources