What HTTP Status Code to Return

When we develop REST APIs, we use HTTP status codes to tell clients whether a request succeeded or failed.

For example, when a client requests employee details, the API returns 200 OK if the employee exists. If the employee is not found, the API returns 404 Not Found.

When a client creates a new employee, the API typically returns 201 Created. When an employee is deleted successfully and no response body is needed, the API can return 204 No Content.

Using the correct HTTP status code is an important part of REST API design. It helps the client understand the response and handle different situations correctly.

In this tutorial, I will explain the most commonly used HTTP status codes for REST APIs. I will also show when to use them with practical examples.

Previous Posts in the Series

HTTP Status Codes

An HTTP status code is a three-digit number returned by the server. It tells the client what happened after processing a request.

HTTP status codes are divided into five categories:

  • 1xx — Informational: The server provides an interim response.
  • 2xx — Success: The server successfully handled the request.
  • 3xx — Redirection: The client may need to follow another URL or use a cached response.
  • 4xx — Client Error: The request has a problem or the client does not have permission.
  • 5xx — Server Error: The server failed to complete the request.

Most Common HTTP Status Codes for REST APIs

The following table shows the HTTP status codes you will use most often when building REST APIs.

HTTP Status CodeWhen to Use It
200 OKRead a resource or return a response body after an update.
201 CreatedCreate a resource; include its URI in the Location header when appropriate.
202 AcceptedAccept a job for asynchronous processing that has not finished.
204 No ContentComplete a deletion or update without returning a response body.
400 Bad RequestReject a malformed request or invalid request parameters.
401 UnauthorizedRequire valid authentication credentials.
403 ForbiddenDeny an action even when the server understands the request.
404 Not FoundRequested resource does not exist or is not disclosed.
409 ConflictRequest conflicts with the current resource state, such as a duplicate unique value.
422 Unprocessable ContentRequest syntax is valid but its instructions cannot be processed.
429 Too Many RequestsClient exceeded a rate limit.
500 Internal Server ErrorUnexpected failure in the API.
503 Service UnavailableTemporary overload or maintenance prevents handling the request.

Success Category (2xx)

Use a 2xx status code when the server successfully handles the request. The exact code depends on the result.

  • 200 OK: The request succeeded. Common for GET and for POST, PUT, or DELETE when a response representation is returned. It is not required for every successful request.
  • 201 Created: The request resulted in one or more new resources. Often used after POST, with a Location header identifying the primary created resource.
  • 202 Accepted: The request has been accepted for processing, but the processing is not complete.
  • 203 Non-Authoritative Information: The request was successful, but the information may be from a third party.
  • 204 No Content: The server fulfilled the request and has no response content to send. Common after DELETE or PUT. Do not include a response body.
  • 205 Reset Content: The server processed the request successfully, and the client should reset the document view.

Redirection Category (3xx)

A 3xx code tells the client that the resource is available elsewhere or that a cached copy can be used.

  • 300 Multiple Choices: The server has multiple options for the resource that the client can choose from.
  • 301 Moved Permanently: The resource has been permanently moved to a new URI.
  • 302 Found: The target resource is temporarily available at another URI. For method-preserving temporary redirects, consider 307 instead.
  • 304 Not Modified: A conditional request indicates that the client's cached representation can be reused. A 304 response has no content body.

Client Error Category (4xx)

Use a 4xx status code when the request cannot be completed because of an issue on the client side. This includes invalid data and access restrictions.

  • 400 Bad Request: The server cannot or will not process a request because of a perceived client error, such as malformed JSON or invalid request syntax.
  • 401 Unauthorized: The request lacks valid authentication credentials. Despite its name, this status concerns authentication and normally includes a WWW-Authenticate challenge.
  • 403 Forbidden: The client does not have access rights to the content.
  • 404 Not Found: The server cannot find the requested resource.
  • 405 Method Not Allowed: The request method is not supported for the requested resource.
  • 406 Not Acceptable: The requested resource is only capable of generating a response that is not acceptable according to the Accept headers sent in the request.
  • 408 Request Timeout: The server timed out waiting for the request.
  • 409 Conflict: The request cannot be completed because it conflicts with the resource's current state, for example an update that clashes with a concurrent change.
  • 413 Content Too Large: The request content exceeds the size limit supported by the server.
  • 415 Unsupported Media Type: The request entity has a media type that the server or resource does not support.
  • 422 Unprocessable Content: The server understands the content type and syntax but cannot process the provided instructions. Some APIs use this for semantic validation failures.
  • 429 Too Many Requests: The client has sent too many requests in a given amount of time.

Server Error Category (5xx)

A 5xx code means the server could not complete the request. For example, an unexpected application error may result in 500 Internal Server Error.

  • 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
  • 501 Not Implemented: The server does not support the functionality required to fulfill the request.
  • 502 Bad Gateway: The server received an invalid response from an upstream server.
  • 503 Service Unavailable: The server is currently unable to handle the request due to a temporary overload or maintenance.
  • 504 Gateway Timeout: The server did not receive a timely response from an upstream server.

Case Study 1: Employee Management System

Let's take an Employee Management application as an example. It provides REST APIs to create, retrieve, update, and delete employees.

Here are the status codes I would typically use for successful operations.

Example Scenarios and Status Codes

  1. Retrieve an Employee by ID:

    • Method: GET
    • URL: /api/v1/employees/100
    • Return HTTP Status Code: 200 OK
  2. Retrieve All Employees:

    • Method: GET
    • URL: /api/v1/employees
    • Return HTTP Status Code: 200 OK
  3. Create a New Employee:

    • Method: POST
    • URL: /api/v1/employees
    • Return HTTP Status Code: 201 Created
  4. Update an Employee by ID:

    • Method: PUT
    • URL: /api/v1/employees/100
    • Return HTTP Status Code: 204 No Content

After creating an employee, the API can return 201 Created with a Location header pointing to the new employee.

For an update, return 200 OK if you send the updated employee in the response. Return 204 No Content if you do not send a response body.

If the requested employee does not exist, return 404 Not Found.

Case Study 2: User Management Application

A User Management application works in a similar way. The following endpoints show common status codes for successful operations.

Example REST APIs and Status Codes

  • GET /api/users - Retrieves all users: 200 OK
  • POST /api/users - Creates a new user: 201 Created
  • GET /api/users/{id} - Retrieves a user by ID: 200 OK
  • PUT /api/users/{id} - Updates a user by ID: 204 No Content
  • DELETE /api/users/{id} - Deletes a user by ID: 204 No Content

These status codes change when a request fails. For example, the API can return 409 Conflict when a user tries to register with an email address that already exists.

If the JSON is malformed, return 400 Bad Request. Use 401 Unauthorized when the client is not authenticated. Use 403 Forbidden when the client is authenticated but does not have the required permission.

More Real-World REST API Use Cases

Let's look at a few more situations you may encounter when developing Spring Boot REST APIs.

1. Product Not Found — 404 Not Found

A client requests GET /api/products/500. The Product Service searches for product 500 but cannot find it.

The API returns 404 Not Found. This is better than returning 200 OK with an error message.

2. Invalid Registration Data — 400 Bad Request or 422 Unprocessable Content

A client sends a registration request without a required email address.

Many REST APIs return 400 Bad Request for failed input validation. Some APIs use 422 Unprocessable Content when the request format is valid but its values cannot be processed. Choose a consistent approach and document it.

3. Duplicate Email Address — 409 Conflict

A user tries to create an account with an email address that is already registered.

If email addresses must be unique, the API can return 409 Conflict. The error response should explain that the email address is already in use.

4. Missing or Invalid Access Token — 401 Unauthorized

A client calls GET /api/orders without valid authentication credentials.

The API returns 401 Unauthorized. The client must authenticate before accessing the protected resource.

5. User Tries to Access an Admin API — 403 Forbidden

A signed-in user calls DELETE /api/admin/users/10. The user does not have the required administrator permission.

The API returns 403 Forbidden. The user is authenticated but is not allowed to perform this operation.

6. Export Report in the Background — 202 Accepted

A client sends POST /api/reports to generate a large report. The application starts the job in the background.

The API returns 202 Accepted because the report is not ready yet. The response can include a URL where the client can check the job status.

7. Rate Limit Exceeded — 429 Too Many Requests

A client sends more requests than the API allows within a short period.

The API returns 429 Too Many Requests. It can also include a Retry-After header to indicate when the client should try again.

8. Service Temporarily Unavailable — 503 Service Unavailable

An API cannot accept new requests because the service is under maintenance or temporarily overloaded.

The API returns 503 Service Unavailable. This tells clients that the problem may be temporary.

9. Unsupported Request Format — 415 Unsupported Media Type

An endpoint expects JSON but the client submits data using a media type the endpoint does not support.

The API can return 415 Unsupported Media Type. The client should send a supported Content-Type.

10. Gateway Waits Too Long — 504 Gateway Timeout

An API Gateway forwards a request to another service. The downstream service does not respond within the allowed time.

The Gateway can return 504 Gateway Timeout. This is different from a client sending an invalid request.

Example HTTP Responses

Creating a Resource: 201 Created

When a POST request creates an employee, the response can identify the newly created resource.

HTTP/1.1 201 Created
Location: /api/v1/employees/101
Content-Type: application/json

{
"id": 101,
"name": "Alex Johnson"
}

Deleting a Resource: 204 No Content

When a deletion succeeds and the API has nothing to return, send the status and no body:

HTTP/1.1 204 No Content

Reporting an Error: 404 Not Found

For errors, it is helpful to include a response body explaining the problem. The RFC 9457 Problem Details format provides a standard structure. Here is an example:

HTTP/1.1 404 Not Found
Content-Type: application/problem+json

{
"type": "about",
"title": "Not Found",
"status": 404,
"detail": "Employee 100 was not found."
}

How to Choose the Right Status Code

Start by checking the result of the request. Then choose the status code that describes it most accurately.

  • Successful request: Use a suitable 2xx code. Select 200 when returning data, 201 after creating a resource, or 204 when there is no response body.
  • Invalid request: Use a suitable 4xx code. For example, use 400 for malformed input and 404 for a resource that cannot be found.
  • Server failure: Use a suitable 5xx code. Return 500 for unexpected internal errors or 503 when the service is temporarily unavailable.
  • Response body: Make sure the chosen status code allows a response body. Do not return JSON with 204 or 304.

Common REST API Status Code Mistakes

These mistakes can make an API difficult to use and debug.

  1. Returning 200 for every request: If an employee does not exist, return 404 instead of reporting success.
  2. Confusing 401 and 403: Use 401 when authentication is missing or invalid. Use 403 when access is not permitted.
  3. Returning 500 for validation errors: Invalid client input should not be treated as an unexpected server failure. Use 400 or 422 according to your API design.
  4. Sending JSON with 204: A 204 response must not contain a response body.
  5. Using 201 for a pending job: If the work has only been accepted and is not finished, use 202 Accepted.

Conclusion

HTTP status codes make REST APIs easier to understand and use. Return the correct code for each operation. Use a 2xx code when the request succeeds. Use a 4xx code for client-side problems and a 5xx code when the server fails.

When building Spring Boot REST APIs, keep your responses consistent across all endpoints. Include useful error messages when needed. This makes it easier for frontend applications and other services to handle API responses correctly.

HTTP Status Code Reference List

This reference includes common and specialized codes as well as a few historical entries. Some are defined by HTTP extensions, some are obsolete or unused, and not all should be implemented in a typical REST API. Consult the official IANA HTTP Status Code Registry and RFC 9110 (HTTP Semantics) for precise definitions and registration status.

1XX Informational

  • 100 Continue
  • 101 Switching Protocols
  • 102 Processing
  • 103 Early Hints

2XX Successful

  • 200 OK
  • 201 Created
  • 202 Accepted
  • 203 Non-Authoritative Information
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content
  • 207 Multi-Status
  • 208 Already Reported
  • 226 IM Used

3XX Redirection

  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found
  • 303 See Other
  • 304 Not Modified
  • 305 Use Proxy
  • 306 Unused (reserved; do not use)
  • 307 Temporary Redirect
  • 308 Permanent Redirect

4XX Client Error

  • 400 Bad Request
  • 401 Unauthorized
  • 402 Payment Required
  • 403 Forbidden
  • 404 Not Found
  • 405 Method Not Allowed
  • 406 Not Acceptable
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Content Too Large (formerly called Payload Too Large)
  • 414 URI Too Long
  • 415 Unsupported Media Type
  • 416 Range Not Satisfiable
  • 417 Expectation Failed
  • 418 I’m a Teapot
  • 421 Misdirected Request
  • 422 Unprocessable Content (formerly called Unprocessable Entity)
  • 423 Locked
  • 424 Failed Dependency
  • 425 Too Early
  • 426 Upgrade Required
  • 428 Precondition Required
  • 429 Too Many Requests
  • 431 Request Header Fields Too Large
  • 451 Unavailable for Legal Reasons

5XX Server Error

  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported
  • 506 Variant Also Negotiates
  • 507 Insufficient Storage
  • 508 Loop Detected
  • 510 Not Extended (obsolete)
  • 511 Network Authentication Required

By understanding the appropriate HTTP status codes to return from your REST API, you can provide clear and useful feedback to clients, enhancing the overall functionality and user experience of your web services.

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments