HTTP status code in RESTful API - paulip114/blog GitHub Wiki
π§ 1. When to return what HTTP status code in RESTful API
Hereβs a cheat sheet of common HTTP status codes and when to use them in a REST API:
Code | Meaning | When to Use It |
---|---|---|
200 OK |
β Success | Successful GET, PUT, PATCH, or DELETE. |
201 Created |
β Resource created | After successful POST creating a resource. |
204 No Content |
β Success, no data | Successful DELETE or update with no response body. |
400 Bad Request |
β Client error | Malformed request (e.g., missing fields, wrong format). |
401 Unauthorized |
β Not authenticated | User not logged in or missing token. |
403 Forbidden |
β Authenticated, but no access | User is logged in, but not allowed to do this. |
404 Not Found |
β Resource missing | Resource (user, file, etc.) doesnβt exist. |
409 Conflict |
β Resource conflict | Duplicate email, username taken, etc. |
422 Unprocessable Entity |
β Validation failed | Data is well-formed but semantically incorrect. |
500 Internal Server Error |
β Server crash | Bug or unhandled server error. |
503 Service Unavailable |
β Server overloaded or down | Often temporary, like for maintenance. |
π§ͺ Examples
POST /users
> 201 Created
GET /users/9999
> 404 Not Found
DELETE /files/abc
> 204 No Content
POST /login (wrong password)
> 401 Unauthorized
π‘ 2. RESTful is Stateless, so why HTTP status codes?
Stateless means:
The server does not store session info about the client between requests.
But HTTP status codes are:
A per-request response, just like the response body.
So they are completely compatible with statelessness.
π Example
You can send a request:
GET /profile
Authorization: Bearer xxx
The server doesn't store anything about the client in memory, but it still replies:
200 OK
{ "name": "Paul" }
Or, if the token is wrong:
401 Unauthorized
So the status code describes what happened in this request only. It doesn't require server-side memory of previous requests.
β Summary
- REST is stateless, but each request gets its own status code response.
- HTTP status codes = way to tell the client what happened.
- Theyβre essential for proper API communication, just like response data.