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.