Client Error Codes: 4xx Range
What you'll learn: How to use 4xx HTTP status codes to clearly communicate client-side mistakes in your REST APIs.
When a client makes a request to your API that can't be fulfilled because they did something wrong, you respond with a status code in the 400s. These codes signal "you made a mistake—fix your request and try again."
The Essential 4xx Codes
400 Bad Request means the request was malformed or invalid. Use this when the client sends syntactically incorrect JSON, missing required fields, or data that violates your API's rules. Think of it like a teacher marking your test "invalid" because you wrote in crayon instead of pen.
401 Unauthorized (despite its confusing name) means "not authenticated." The client needs to provide valid credentials before accessing this resource. It's like trying to enter a building without showing your ID badge—you might be authorized once you authenticate, but right now, we don't know who you are.
403 Forbidden means "authenticated but not authorized." The server knows who you are, but you don't have permission for this action. You showed your ID badge, but you're not allowed in the executive suite.
404 Not Found means the requested resource doesn't exist. The endpoint is valid, but the specific item (like /users/99999 where user 99999 doesn't exist) isn't there. It's like going to the right library but asking for a book that was never published.
Choosing the Right Code
Use 400 for client mistakes in request format, 401 when credentials are missing or invalid, 403 when access is properly denied to a known user, and 404 when a resource simply doesn't exist.
Key Takeaway: 4xx codes tell the client "this is your fault"—use 400 for bad requests, 401 for missing authentication, 403 for insufficient permissions, and 404 for nonexistent resources.