CRUD and Correct HTTP Semantics
Implement create, read, update, and delete operations using appropriate HTTP semantics.
Creating Resources with POST
A typical creation endpoint is POST /users. The client submits a representation without choosing the server-generated identifier.
A successful creation commonly returns 201 Created and a Location header identifying the new resource.
POST /users
Content-Type: application/json
{"name":"Suriya","email":"suriya@example.com"}
Response:
HTTP/1.1 201 Created
Location: /users/42
Content-Type: application/json
{"id":42,"name":"Suriya","email":"suriya@example.com"}
The server should validate the request, enforce business constraints, persist the resource, and return a representation appropriate for the API contract.
app.post('/users', async (req, res) => {
const user = await userService.create(req.body);
res.status(201).location(`/users/${user.id}`).json(user);
});Reading, Updating and Deleting Resources
GET /users/42 retrieves a resource. PUT /users/42 replaces its representation. PATCH /users/42 modifies selected fields. DELETE /users/42 requests deletion.
A common mistake is using POST for every operation. Doing so loses HTTP semantics that clients, proxies, caches, monitoring tools, and retry systems can understand.
For DELETE, repeated requests should generally leave the system in the same desired state, although an API may choose whether a second deletion returns 404 or another documented result.
POST /usersGET /usersGET /users/42PUT /users/42PATCH /users/42DELETE /users/42Safe and Idempotent Methods
A method is safe when it is intended only for retrieval and does not request a state-changing operation. GET, HEAD, and OPTIONS are safe.
A method is idempotent when making the same request multiple times has the same intended effect as making it once. GET, HEAD, PUT, DELETE, and OPTIONS have idempotent semantics.
Idempotency does not mean the response must be byte-for-byte identical. A DELETE request might return 204 the first time and 404 later while the intended resource state remains deleted.
Idempotency is critical for retries in distributed systems.
Why is idempotency important for APIs?