Which HTTP status codes should a REST API return for create, validation errors, missing login and forbidden access?
201 Created for a successful create, 400 for bad input (or 422 for failed validation), 401 when the user is not authenticated, 403 when authenticated but not allowed, 404 for a missing resource, and 500 for server faults.
Explain it simply
Status codes are one-word answers from the server. The first digit tells the story: 2xx means it worked, 4xx means the client made a mistake, 5xx means the server failed.
| Situation | Code |
|---|---|
| Fetched or updated successfully | 200 OK |
| New record created | 201 Created (with the new record or a Location header) |
| Deleted, nothing to return | 204 No Content |
| Malformed JSON or missing field | 400 Bad Request |
| Valid JSON but breaks a rule | 422 Unprocessable Entity (many teams just use 400) |
| No token, or token invalid | 401 Unauthorized |
| Logged in, but not an admin | 403 Forbidden |
| ID does not exist | 404 Not Found |
| Email already registered | 409 Conflict |
| Too many requests | 429 Too Many Requests |
| Unexpected crash | 500 Internal Server Error |
Example
app.post("/api/students", async (req, res) => {
if (!req.body.email) {
return res.status(400).json({ error: "email is required" });
}
const exists = await Student.findOne({ email: req.body.email });
if (exists) return res.status(409).json({ error: "email already used" });
const student = await Student.create(req.body);
res.status(201).json(student);
});Despite its name, 401 means "not authenticated" (who are you?), while 403 means "not authorised" (I know you, but no).
What to say in the interview
"2xx success with 201 for creates, 400 or 422 for bad input, 401 for missing or bad credentials, 403 for insufficient permission, 404 and 409 for missing or conflicting resources, 5xx only for server faults."
Common mistakes
- Returning 200 with
{ "success": false }for errors. - Mixing up 401 and 403.