brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Answer POST with 201 Created and a Location header

Curl
~/tips/tip-rest-201-created-location-header

curl -si -X POST -H 'Content-Type: application/json' \

A 201 response with a Location header tells the client where the newly created resource lives.

When an API creates something, the client wants to know where it ended up. A 200 with a body works, but HTTP has a more precise answer that plain tools like curl show without any parsing.

curl -si -X POST -H 'Content-Type: application/json' \
  -d '{"name":"widget"}' http://localhost:8000/items

Against a small Python test server, curl 8.5.0 printed this:

HTTP/1.0 201 Created
Content-Type: application/json
Location: /items/42

{"id":42,"name":"widget"}

RFC 9110 says 201 means the request has been fulfilled and resulted in one or more new resources. The primary resource is identified by the Location header or, when there is none, by the target URI. The response content typically describes and links to the new resource.

In a script, the header is easy to pull out on its own:

curl -s -o /dev/null -D - -X POST -d '{}' http://localhost:8000/items | grep -i '^location:'

One caveat is about validators. If the response carries an ETag or Last-Modified, the RFC says they describe the new representation. For PUT, it adds that the method has extra requirements that might rule such validators out. So don’t attach an ETag to a 201 reflexively.

My rule of thumb is to reserve 201 for requests that created a resource. For anything else, a 200 with the result is the plainer answer.

Further reading: RFC 9110, section 15.3.2 201 Created

More Curl tips curl --oauth2-bearer "$TOKEN" https://api.example.com/v1/items – trigger: webhook curl --trace-ascii – https://example.com/ Retry-After: 120 curl -fsS --fail-early \ All Curl tips (74) All topics

Link