Answer
Testing 4xx Status Codes in API Projects
In API testing, it''s not sufficient to only test success scenarios. We also need to test client-side errors (4xx) effectively.
400 Bad Request
When: Request is malformed or missing required fields.
POST /api/orders
Content-Type: application/json
{ "product": "12345" } // Missing: customer, quantity
Response: 400 Bad Request
{ "error": "Missing required fields: ''customer'', ''quantity''" }
given()
.body("{ \"product\": \"12345\" }")
.contentType(ContentType.JSON)
.when()
.post("/api/orders")
.then()
.statusCode(400)
.body("error", containsString("Missing required fields"));
401 Unauthorized
When: Missing or invalid authentication token.
GET /api/profile
// No Authorization header
Response: 401 Unauthorized
{ "error": "Invalid credentials" }
given()
.when()
.get("/api/profile") // no auth header
.then()
.statusCode(401);
403 Forbidden
When: Authenticated but lacks permission for the resource.
DELETE /api/users/123
Authorization: Bearer <normal-user-token>
Response: 403 Forbidden
{ "error": "Insufficient permissions to delete user" }
given()
.header("Authorization", "Bearer normal-user-token")
.when()
.delete("/api/users/123")
.then()
.statusCode(403)
.body("error", containsString("Insufficient permissions"));
404 Not Found
When: Requested resource does not exist.
GET /api/users/999 // user 999 doesn't exist
Response: 404 Not Found
{ "error": "User not found" }
405 Method Not Allowed
When: Endpoint does not support the HTTP method used.
PUT /api/customers/123 // endpoint only allows GET and POST
Response: 405 Method Not Allowed
{ "error": "PUT method is not allowed for this endpoint" }
Tip: Always use OPTIONS to cross-check what methods are allowed before testing!
422 Unprocessable Entity
When: Request body is syntactically correct but semantically invalid (e.g., invalid email format, future birth date).
given()
.body("{ \"email\": \"not-an-email\" }")
.contentType(ContentType.JSON)
.when()
.post("/api/users")
.then()
.statusCode(422)
.body("error", containsString("Invalid email format"));
