REST API Design Best Practices

Chapter 2 · Practice 2 of 4

Create with POST to a collection and return 201 with Location

From HTTP methods and their promises

Why it matters

POST /orders asks the server to create a new order and pick its id. On success, return:

  • 201 Created
  • a Location header with the new resource's URL
  • the created resource in the body, so the client does not need a second request

Use PUT for creation only when the client chooses the id (PUT /users/me/avatar, PUT /settings/theme). Because PUT replaces the whole resource at that URL, repeating it is harmless, which is what makes it idempotent.

Because POST is not idempotent, a client that times out does not know whether the order was created. The idempotency chapter shows how to make retries safe.

Example

HTTP
POST /orders
Content-Type: application/json

{ "sku": "A1", "quantity": 2 }

HTTP/1.1 201 Created
Location: /orders/ord_8f3k2
Content-Type: application/json

{ "id": "ord_8f3k2", "status": "pending", "sku": "A1", "quantity": 2 }