HTTP verbs, URLs and status codes (REST)

A web request carries a verb that says what to do and a URL that says what to do it to. The server replies with a status code.

Browsing the menu of a food delivery app, you add an item and tap Place order. A minute later you change the quantity. Then you cancel the order. Each of these taps sends one request from your phone to the app's server.

Your phoneSends each request
The app's serverReads it and replies
The databaseStores the orders
Think first. You tap Place order, the screen freezes, and you tap it again. Could the app now hold two orders? What would you need to know to be sure?
Ask students to name what the Place order tap sent (the verb). Listen for the idea that tapping again sends the same request again, and for whether they think the result depends on the verb.

The table holds three orders. A request is a verb and a URL, plus a body when it carries data. POST asks the server to create an order. Press Send, then Send again, and count the rows.

orders 3 rows
orderitemqtytip (₱)
Pick a request
More detail

Try the other requests

Pick another request in the list and send it twice. PUT and PATCH show a body you can edit. Untick a field and compare what each verb does with the missing value. Send DELETE twice and the second reply is 404.

Order number

The number in the first column is the order's id, and the URL uses it, such as /orders/8888. You do not send an id when you create an order. The server assigns the next free one and returns it, and the id never changes after that.

One request or fifty?

An order history page lists a user's past orders and needs the item names for each one. You can fetch the list and then fetch each order in turn, or you can design an endpoint (a URL the server answers) that returns everything in one request. A round trip is one request and its reply, and Round trips and latency shows what each one costs. A handler is the code on the server that answers one request.

Fetching 50 orders
 one at a timeone request
Settings
The model uses a 38 ms round trip, about 700 bytes of request headers per request (cookies, user agent, accept) and 120 bytes per order.

Over HTTP/1.1 a browser opens six connections to one host, so fifty-one requests wait in batches of six. HTTP/2 is a newer version of the protocol that sends many requests at once over one connection. Turn it on and watch which numbers change and which do not.

When fetching everything is wasteful

The first widget fetched fifty orders because the page needed all fifty. Many lists are different. A search returns five hundred results and the user scrolls past a dozen. Fetching all of them in one request is efficient for each item and wasteful overall, and the first screen waits for data nobody asked to see.

A 500-result search, 20 per page
 everything up frontas they scroll
How far does the user scroll?
The model uses the same 38 ms round trip, 120 bytes per result and a connection that moves about a megabyte per second.

Drag the slider all the way right to see a user who reads every result. Even then, check which row still favors loading as the user scrolls.

Choosing how much an endpoint returns

Both designs fail for the same reason: the endpoint was designed without knowing what the page does with it. One request per item costs a round trip each. One request for everything moves data nobody scrolls to. In both cases the fix is to add a parameter to the endpoint. GET /orders?ids=8888,8889 returns exactly the missing pieces in one trip. GET /orders?include=items lets the caller choose how much detail to receive. GET /orders?limit=20&offset=40 lets the caller ask for one slice, which is called pagination.

To decide, ask how many of the returned items will be looked at, and how soon the reader needs the first one. If every client loops over your list endpoint to fill in gaps, the endpoint returned too little. If most of what you send is never scrolled to, it returned too much.

Two properties tell you how risky a verb is to repeat. A verb is safe if it changes nothing. It is idempotent if sending it twice gives the same result as sending it once. Select each verb and read what happens when you send it twice.

More detail

The same verb on a collection and on one item

A collection is a list of items, such as /orders. One item is a single entry, such as /orders/8888. Select a cell to see what that combination means and what it returns.

Verb On a collection  /orders On one item  /orders/8888
Select a cell

The meaning appears here.

Naming URLs

A URL should name a thing, such as orders or users, and the verb says what to do with it. A common first mistake is to put the action in the URL.

✕ Verbs inside the URL
  • GET /getOrders
  • GET /createOrder?item=2
  • POST /updateOrderQty
  • GET /cancelOrder?id=5

Every new action needs a new URL, so the list keeps growing. The fourth one also changes data behind a GET. A search engine crawler (a program that follows links) could cancel your users' orders.

✓ Nouns in the URL, verb in the method
  • GET    /orders
  • POST   /orders
  • PATCH  /orders/8888
  • DELETE /orders/8888

A small fixed set of verbs works with a growing set of nouns. Anyone who knows HTTP can guess your URLs without reading documentation. A predictable URL scheme is one of the main benefits of REST.

What REST asks of you

REST is a set of conventions for using verbs, URLs and status codes together. Model your system as resources: the nouns your users talk about, such as orders, menu items and users. Give each resource a URL. Act on resources with the standard verbs. Let the status code report the outcome. Keep each request self-contained, so the server does not need to remember the previous one. This is called being stateless. Stateless servers are easier to copy onto many machines, as Load balancers and scaling shows.

Full example requests

GET /orders/8888 HTTP/1.1 POST /orders HTTP/1.1 Content-Type: application/json {"item":"Chicken rice","qty":2,"tip":20} PUT /orders/8888 HTTP/1.1 Content-Type: application/json {"item":"Beef noodles","qty":1,"tip":0} PATCH /orders/8888 HTTP/1.1 Content-Type: application/json {"qty":3} DELETE /orders/8888 HTTP/1.1

POST needs protection that you build, such as a unique constraint (a database rule that rejects duplicates) or an idempotency key (a unique code the client sends with each request). Payments and gateways shows the second one at work.

In Django, Express and Laravel

A web framework is a toolkit for writing servers. Each one checks which verb arrived and runs the matching code.

VerbDjangoExpressLaravel
GETrequest.method == "GET" runs your list or detail viewrouter.get(path, handler) runs your list or detail routeRoute::get(...) runs index() or show()
POSTrequest.method == "POST" calls form.save() or Model.objects.create()router.post(...) calls prisma.model.create({ data })Route::post(...) calls Model::create($validated)
PUTrequest.method == "PUT" overwrites every field on the instancerouter.put(...) calls prisma.model.update({ where, data })Route::put(...) calls $model->update($all)
PATCHrequest.method == "PATCH" updates only the keys you were sentrouter.patch(...) updates only the keys you were sentRoute::patch(...) calls $model->fill($partial)->save()
DELETErequest.method == "DELETE" calls instance.delete()router.delete(...) calls prisma.model.delete({ where })Route::delete(...) calls $model->delete()

Every reply from a server starts with a status code. The first digit says which kind of reply it is.

1xx
Informational
The server is still working. You will rarely see these.
2xx
Success
The request worked. The codes differ in what came back.
3xx
Redirect
Go to another URL, or use the copy you already have.
4xx
Client error
The request was wrong. The server is working. Fix the request.
5xx
Server error
The request was fine. The server failed. Its logs show why.

Select 401 and 403, then 404 and 500. Each explanation says where to look first.

Select a code

The meaning appears here.

You can now pick the right verb for a task and read a status code.

More detail

Two pairs that are easy to mix up

401 and 403

401 Unauthorized means the server does not know who you are. The name is misleading, because the real meaning is unauthenticated. Send your login details and try again.

403 Forbidden means the server knows who you are and still says no. Better credentials will not help, because you are not allowed.

404 and 500

404 and 500 both look like a broken page to a user, and they point to different places to look.

404 means the URL names nothing, so check the request, the path and the id. 500 means the server code failed with an error, so read the server's error report (called a traceback) and ignore the page itself.

More status codes