Status Code Validation

Introduction

Every HTTP response returned by an API contains a status code. It is one of the first signals a client receives after sending a request because it tells whether the request succeeded, failed, redirected, was rejected because of a client-side problem, or failed because of a server-side problem. Status codes are small numeric values, but they carry important meaning in API communication.

For example, a login API should return 200 OK when valid credentials are accepted. The same login API should return 401 Unauthorized when credentials are missing or invalid. A resource creation API should usually return 201 Created after successfully creating a new resource. A delete API may return 204 No Content after deletion. A request for a missing resource may return 404 Not Found. A malformed JSON request may return 400 Bad Request. These responses help clients understand what happened and what to do next.

Status code validation is one of the most fundamental techniques in API testing. It verifies whether the API returns the correct HTTP status code for a specific request and scenario. However, status code validation should not be treated as the only validation. A response can return 200 OK and still contain wrong data. A response can return 400 Bad Request and still provide an unclear or insecure error body. Status code, response headers, response body, and business outcome must be validated together for complete API correctness.

This tutorial explains status code validation from a practical testing perspective. It covers what status code validation means, why it matters, the five status code categories, common success, redirect, client error, and server error codes, real-world test cases, examples in REST Assured, Postman, and Karate, best practices, mistakes, and interview-ready explanations.

What Is Status Code Validation?

Status code validation is the process of verifying that an API returns the expected HTTP status code for a given request, input data, user state, permission level, and business scenario. In simple terms, it is checking whether the API communicates the result of the request using the correct HTTP response code.

If the request is successful, the API should return an appropriate success code, such as 200, 201, 202, or 204. If the client sends invalid data, the API should return an appropriate client error code, such as 400 or 422, depending on the API design. If authentication is missing, 401 is usually expected. If authentication is valid but permission is missing, 403 is usually expected. If the requested resource does not exist, 404 is common.

Status code validation is not about memorizing numbers blindly. It is about matching API behavior to the HTTP standard, the API specification, and the business scenario. A well-designed API uses status codes consistently so clients can handle responses predictably. A poorly designed API may return 200 OK for everything and hide errors inside the body, which makes integration and debugging harder.

For testers, status code validation provides a quick and reliable first check. It confirms that the API classified the result correctly. Once the status code is verified, the tester should validate headers, body structure, field values, error messages, and business rules.

Why Status Code Validation Is Important

Status codes help clients understand what happened without parsing the entire response body first. A client can immediately know whether the request succeeded, failed due to bad input, failed because authentication is missing, failed because permission is denied, redirected to another location, or encountered a server-side issue. This makes client-server communication more reliable.

Correct status codes also improve debugging. If a request with invalid JSON returns 400 Bad Request, the tester knows the client request is the problem. If the same request returns 500 Internal Server Error, it suggests the server may not be handling malformed input safely. If a request without a token returns 200 OK, there may be a serious security defect. If a duplicate resource returns 409 Conflict, the response clearly communicates the nature of the failure.

Status codes are also important for automation, monitoring, gateways, load balancers, retries, and client logic. Many systems use status codes to decide whether to retry, log an error, show a validation message, refresh a token, follow a redirect, or open a circuit breaker. Incorrect codes can mislead these systems. For example, returning 500 for a user validation error may trigger unnecessary incident alerts or retries.

API specifications such as OpenAPI usually document expected status codes for each endpoint. Validating status codes ensures the implementation follows that contract. It also helps maintain consistency across endpoints, which is important as APIs grow across multiple teams and services.

HTTP Status Code Categories

HTTP status codes are grouped into five broad categories. Codes in the 1xx range are informational. Codes in the 2xx range indicate success. Codes in the 3xx range indicate redirection. Codes in the 4xx range indicate that the client request has a problem. Codes in the 5xx range indicate that the server or an upstream service has a problem.

This grouping helps testers reason about responses before focusing on specific codes. A valid GET request should usually return a 2xx code. A missing resource should usually return a 4xx code, not a 5xx code. A temporarily unavailable service may return 503. A moved resource may return a 3xx redirect. The first digit gives a high-level classification of the response.

Understanding categories also helps in interviews. Instead of listing random codes, a strong answer explains what each category means and then gives practical examples. Testers should know the codes they see most often in API testing: 200, 201, 202, 204, 301, 302, 304, 400, 401, 403, 404, 405, 409, 415, 422, 429, 500, 502, 503, and 504.

1xx Informational Codes

1xx status codes indicate that the request has been received and processing is continuing. These codes are part of HTTP, but they are not commonly validated in everyday REST API functional testing. One known example is 100 Continue, which can be used when a client wants confirmation before sending a large request body.

100 Continue

In most API testing tools, testers mainly work with final responses such as 200, 400, or 500. Informational responses may be handled by the HTTP client library before the tester sees the final result. Still, knowing the category is useful because it completes the HTTP status code picture.

Advanced testing may involve 1xx behavior when dealing with large uploads, proxies, gateways, streaming, or lower-level HTTP behavior. For most application API testers, 1xx codes are less common than 2xx, 4xx, and 5xx responses.

2xx Success Codes

2xx status codes indicate that the request was successfully received, understood, and processed. These are common in happy-path API testing. The most frequently used success codes are 200 OK, 201 Created, 202 Accepted, and 204 No Content.

200 OK is commonly returned for successful GET requests and many successful operations. For example, GET /users/101 may return 200 OK with a user object in the response body. Testers should validate that the status code is 200 and that the body contains the correct user data.

GET /users/101
Expected: 200 OK

201 Created is commonly used after a new resource is created, such as POST /users. The response may include the created resource in the body and a Location header pointing to the new resource. Testers should validate the status code, response body, and Location header when required.

POST /users
Expected: 201 Created

202 Accepted means the request has been accepted for processing, but processing has not necessarily completed. This is common in asynchronous systems such as report generation, batch processing, file conversion, or long-running jobs. Testers should verify that the response provides a way to check the job status later.

204 No Content means the operation succeeded and there is no response body. It is common for delete operations or updates that do not return data. If 204 is expected, the response body should be empty. Returning a JSON body with 204 is usually inconsistent because 204 specifically means no content.

3xx Redirection Codes

3xx status codes indicate that the client needs to take additional action to complete the request, usually by following a Location header. Redirection codes are common in web browsing and can also appear in APIs, especially when resources move, authentication flows redirect, or cached content is still valid.

301 Moved Permanently means the resource has permanently moved to a new URL. The response usually includes a Location header. 302 Found indicates a temporary redirect. 307 Temporary Redirect and 308 Permanent Redirect preserve the original method more strictly than older redirect behavior. Testers should validate both the status code and Location header for redirect scenarios.

HTTP/1.1 301 Moved Permanently
Location: https://example.com/new-resource

304 Not Modified is used for conditional requests. If a client already has a cached version and sends headers such as If-None-Match or If-Modified-Since, the server can return 304 to indicate the cached copy is still valid. A 304 response does not include a response body. This status code is important for caching and performance behavior.

API testers should not ignore redirects. Unexpected redirects can break API clients, expose open redirect risks, or hide authentication issues. If an API endpoint should return JSON but instead redirects to an HTML login page, that may be a defect for API consumers.

4xx Client Error Codes

4xx status codes indicate that the client's request has a problem. These are central to negative API testing because testers intentionally send invalid input, missing headers, unauthorized requests, unsupported content types, duplicate data, and invalid parameters to verify that the API rejects them correctly.

400 Bad Request is commonly used when the request is malformed or invalid. Examples include invalid JSON, missing required fields, wrong data types, invalid query parameters, or general validation failures depending on API design. If the API uses 422 for semantic validation, then 400 may be reserved for malformed syntax or basic request problems.

{
  "name":
}

This invalid JSON should not produce 500 Internal Server Error. It should produce a controlled client error, commonly 400 Bad Request.

401 Unauthorized means authentication is missing, invalid, expired, or not accepted. Despite the name, it is about authentication, not permission. A missing bearer token or expired token commonly returns 401. 403 Forbidden means the client is authenticated but does not have permission for the requested action. For example, a normal user trying to delete an admin-only resource may receive 403.

404 Not Found means the requested resource or endpoint could not be found. For example, GET /users/999999 may return 404 if that user does not exist. 405 Method Not Allowed means the endpoint exists but does not support the HTTP method used. 409 Conflict is often used for duplicate resources or state conflicts. 415 Unsupported Media Type means the Content-Type is not supported. 422 Unprocessable Content is commonly used when the request is syntactically valid but semantically invalid. 429 Too Many Requests means the caller exceeded the rate limit.

5xx Server Error Codes

5xx status codes indicate that the server or an upstream system failed to process a valid request. These are not usually expected during normal functional testing, but testers should understand them because they appear during outages, infrastructure issues, unhandled exceptions, dependency failures, timeouts, and gateway problems.

500 Internal Server Error indicates an unexpected server failure. It is a broad error and should not be used for normal validation failures. If a user sends invalid email, returning 500 suggests poor error handling. Client-side mistakes should generally produce 4xx responses.

502 Bad Gateway means a gateway or proxy received an invalid response from an upstream server. 503 Service Unavailable means the server is temporarily unable to handle the request, often due to maintenance, overload, or dependency outage. 504 Gateway Timeout means a gateway did not receive a timely response from an upstream service.

In API testing, 5xx responses should be investigated carefully. They may indicate defects, environment instability, dependency failures, data setup problems, or infrastructure issues. Automated tests should usually fail when unexpected 5xx responses occur. Monitoring systems also rely heavily on 5xx rates to detect service health problems.

Status Code Validation in API Testing

Status code validation should be included for every API request. For successful requests, testers verify expected success codes such as 200, 201, 202, and 204. For invalid requests, testers verify appropriate client error responses such as 400, 401, 403, 404, 405, 409, 415, 422, and 429. For server failure scenarios, where they can be safely simulated, testers may verify 500, 502, 503, or 504 behavior.

A good status code test is scenario-specific. A valid login request should not merely expect any 2xx response; it should expect the documented success code. If the API contract says successful login returns 200, then 201 would be incorrect. A create user request may expect 201, not 200. A delete request may expect 204, not 200. Exact expectations make tests more meaningful.

For negative testing, status code choice should match the reason for failure. Missing authentication should usually not return 400. Lack of permission should usually not return 401 if the user is already authenticated. Duplicate creation should usually not return 500. Wrong Content-Type should usually not return a generic validation error if the API has a documented 415 behavior. These distinctions improve API quality.

Status Code and Response Body Must Agree

Status code validation must be performed together with response body validation. A response that returns 200 OK with an error message in the body is often a poor API design because clients may treat the operation as successful. Similarly, a response that returns 400 Bad Request with a body saying success true is inconsistent.

For example, this response is misleading:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "success": false,
  "error": "Invalid credentials"
}

For invalid credentials, 401 Unauthorized is usually more appropriate. The response body can still explain the error, but the status code should communicate failure clearly. Client applications, monitoring tools, and gateways depend on status codes.

Testers should validate that success codes have success bodies and error codes have error bodies. The status code, headers, body, and actual business state should all tell the same story. If they do not, the API contract is unclear or the implementation is defective.

Status Code and Response Headers Must Agree

Response headers also need to match the status code. A 201 Created response may include a Location header pointing to the created resource. A 204 No Content response should not include a meaningful response body and should be treated as empty content. A 304 Not Modified response should not include a response body. A 429 Too Many Requests response may include Retry-After. A redirect response should include Location.

These relationships help testers create stronger validations. Checking only the number misses part of the behavior. For a file download, the status code may be 200, but Content-Type, Content-Length, and Content-Disposition may still be wrong. For a redirect, the status code may be 302, but the Location header may point to an unsafe or incorrect URL.

Status code validation is strongest when combined with header expectations. This is especially true for redirects, creation, caching, rate limiting, authentication, and no-content responses.

Status Code Validation Checklist

A practical status code validation checklist includes the expected status code, response body consistency, response header consistency, error message quality, business logic, API specification compliance, consistency across endpoints, and behavior for positive, negative, authorization, authentication, rate limit, and server failure scenarios.

For successful requests, confirm that the API returns the exact expected success code and correct response body. For invalid requests, confirm that the API returns the documented client error code and a useful error response. For unauthorized requests, confirm correct 401 behavior. For forbidden requests, confirm correct 403 behavior. For missing resources, confirm 404 behavior. For unsupported methods, confirm 405 behavior. For unsupported media types, confirm 415 behavior. For duplicate or conflicting state, confirm 409 behavior if the API uses it.

The checklist should be adjusted to the endpoint. A login endpoint needs 200 and 401 checks. A role-restricted endpoint needs 403 checks. A creation endpoint needs 201 and duplicate conflict checks. A file upload endpoint needs success, validation, unsupported type, and oversized file checks. A rate-limited endpoint needs 429 checks.

Real-World Test Cases

A login API is a simple but useful example. Valid credentials should return 200 OK with authentication data or session information. Invalid credentials should return 401 Unauthorized. Missing credentials may return 400 or 401 depending on the API design. An inactive user may return 403, 423, or another documented code depending on business rules.

A create user API usually returns 201 Created when a new user is created. If the email already exists, the API may return 409 Conflict. If the JSON is malformed, it should return 400 Bad Request. If required fields are missing, the API may return 400 or 422 depending on the specification. If the caller lacks permission to create users, it should return 403.

A delete user API may return 204 No Content when deletion succeeds. If the user does not exist, it may return 404. If the caller is not authenticated, it should return 401. If the caller is authenticated but not allowed to delete users, it should return 403. If the delete operation is blocked because the user has active dependencies, the API may return 409 Conflict.

These examples show why status code validation must be tied to scenario intent. The same endpoint can return many different valid status codes depending on request data, user permissions, resource state, and business rules.

REST Assured Example

REST Assured makes status code validation straightforward. A simple GET validation may look like this:

given()
.when()
  .get("/users/101")
.then()
  .statusCode(200);

A create request may validate 201 Created:

given()
  .contentType("application/json")
  .body(requestBody)
.when()
  .post("/users")
.then()
  .statusCode(201);

A negative test may send invalid JSON or invalid data and expect 400 or 422 based on the contract:

given()
  .contentType("application/json")
  .body(invalidRequestBody)
.when()
  .post("/users")
.then()
  .statusCode(400);

In real automation, the test should usually validate more than the status code. It should also validate error message, response schema, important headers, and business state. REST Assured supports all of these checks, so status code assertions should be the starting point, not the full test.

Postman Example

Postman can validate status codes in the Tests tab. A simple check is:

pm.test("Status code is 200", function () {
  pm.response.to.have.status(200);
});

For a create user request, the expected code may be 201:

pm.test("User created", function () {
  pm.response.to.have.status(201);
});

For negative tests, Postman can validate expected error codes and response bodies. Collections can include separate requests for valid credentials, invalid credentials, missing token, forbidden access, missing resource, invalid JSON, duplicate resource, and rate limit behavior. Newman can run those collections in CI pipelines.

Postman is also useful for exploring unexpected status codes. If a request returns 500 when 400 is expected, testers can inspect the request body, headers, environment variables, authorization setup, and server response details before logging a defect.

Karate Example

Karate uses concise syntax for status code validation:

When method GET
Then status 200

A POST validation may look like this:

Given request
"""
{
  "name": "John"
}
"""
When method POST
Then status 201

Karate can also combine status code validation with response body checks:

Then status 400
And match response.message contains 'Email is required'

This style keeps API behavior readable. The scenario clearly states the expected response code and can also validate error content, headers, and response structure. As with other frameworks, tests should align with the API specification.

Best Practices

Validate the status code for every API request. Use exact expected codes when the contract is clear. Do not accept any 2xx response unless the endpoint truly allows multiple success codes. Exact checks make tests more precise and catch unintended behavior changes.

Do not assume 200 OK means the API is correct. Always validate response body and response headers where relevant. A 200 response with wrong data, missing fields, unsafe cache headers, or exposed sensitive information is still a defect. Status code validation should be part of a broader validation strategy.

Follow the API specification for expected status codes. If the specification says validation errors return 422, tests should expect 422. If the project standard uses 400 for validation errors, tests should expect 400. Consistency matters more than personal preference. When the API behavior and specification disagree, raise the mismatch clearly.

Test both positive and negative scenarios. Happy-path testing confirms success behavior, but negative testing confirms that the API rejects bad requests safely. Include authentication, authorization, malformed input, missing resource, wrong method, unsupported media type, duplicate resource, and rate limit cases where applicable.

Common Mistakes

The most common mistake is checking only the status code. A response may return 200 OK but contain incomplete business data. It may return 201 Created but fail to persist the resource. It may return 400 but provide no useful field-level error. It may return 204 but still send a response body. Status code checks are necessary, but they are not sufficient.

Another mistake is returning 200 for errors. Some APIs return 200 OK with an error message inside the body. This forces every client to parse the body to know whether the request actually succeeded. It can break monitoring, retries, gateway behavior, and integration logic. Whenever possible, APIs should use appropriate HTTP error status codes.

Returning 500 for validation errors is also a serious mistake. Invalid client input should usually return a 4xx response, not a server error. A 500 response suggests the server failed unexpectedly. If malformed JSON or missing email causes 500, the API is not handling invalid requests correctly.

A further mistake is using inconsistent codes across endpoints. One create endpoint returns 201, another returns 200, and another returns 204 for similar behavior. One validation failure returns 400 and another returns 500. Inconsistency makes clients harder to build and tests harder to maintain.

Interview Questions

A common interview question is: what is status code validation? A strong answer is that status code validation is the process of verifying that an API returns the correct HTTP status code for a given request and scenario based on the API specification, HTTP standards, and business logic.

Another question is: why is status code validation important? It ensures correct API behavior, proper client-server communication, reliable integrations, predictable error handling, and HTTP standard compliance. It also helps clients and monitoring systems understand whether a request succeeded, failed, redirected, or encountered a server issue.

Interviewers may ask whether API testing should validate only the status code. The answer is no. API testing should validate status code, response headers, response body, business logic, schema, security behavior, and performance where applicable. Status code validation is the first check, not the complete test.

They may also ask for common status codes. A practical answer includes 200 OK, 201 Created, 202 Accepted, 204 No Content, 301 and 302 redirects, 304 Not Modified, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed, 409 Conflict, 415 Unsupported Media Type, 422 Unprocessable Content, 429 Too Many Requests, 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout.

Interview-Ready Explanation

Status code validation is the process of verifying that an API returns the correct HTTP status code based on the request, business logic, and API specification. HTTP status codes indicate whether a request was successful, redirected, rejected because of client-side errors, or failed because of server-side issues. During API testing, testers validate success codes such as 200 OK, 201 Created, 202 Accepted, and 204 No Content, client error codes such as 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed, 409 Conflict, 415 Unsupported Media Type, 422 Unprocessable Content, and 429 Too Many Requests, as well as server error codes such as 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout.

Status code validation is important because clients, automation, gateways, monitoring systems, and integrations depend on status codes to understand the result of a request. Correct codes improve error handling and debugging. Incorrect codes can mislead clients, hide defects, trigger wrong retries, or make failures difficult to diagnose.

Status code validation should always be performed together with response body and response header validation. A correct status code alone does not guarantee API correctness. The response body must contain correct business data or useful error information, and the response headers must match the behavior expected for that status code.

Key Takeaway

Status code validation is a core API testing skill. It confirms that the API communicates the result of a request using the correct HTTP status code. It helps verify success behavior, client errors, authentication failures, authorization failures, missing resources, unsupported methods, unsupported media types, conflicts, rate limits, redirects, and server failures.

The practical rule is simple: validate the exact status code expected for the scenario, then validate the response body, headers, and business outcome. A reliable API does not merely return a response; it returns the right status code with consistent headers and meaningful content. That consistency is what makes APIs easier to use, test, debug, monitor, and integrate.