Sobes.tech
Junior

Tell me about HTTP status codes.

sobes.tech AI

Answer from AI

HTTP status codes are three-digit numbers indicating the state of a client's request after receiving it from the server. They are grouped by the first digit:

  • 1xx (Informational): Request received, processing.
  • 2xx (Successful): Request successfully received, understood, and accepted.
  • 3xx (Redirection): Additional actions are needed to complete the request.
  • 4xx (Client Error): The server cannot process the request due to a presumed client error.
  • 5xx (Server Error): The server failed to process a correctly formed request.

Most common codes:

Code Description Group
100 Continue Informational
200 OK Successful
201 Created Successful
204 No Content Successful
301 Moved Permanently Redirection
302 Found Redirection
400 Bad Request Client Error
401 Unauthorized Client Error
403 Forbidden Client Error
404 Not Found Client Error
500 Internal Server Error Server Error
503 Service Unavailable Server Error

In testing, we verify the correctness of status codes in server responses to ensure that the backend correctly handles various request types (successful, client errors, server issues). This is critical for API logic validation.

Automating status code checks:

import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)

# Check for status 200
assert response.status_code == 200, f"Expected status code 200, but got {response.status_code}"

url_not_found = "https://jsonplaceholder.typicode.com/posts/999"
response_not_found = requests.get(url_not_found)

# Check for status 404
assert response_not_found.status_code == 404, f"Expected status code 404, but got {response_not_found.status_code}"
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class ApiStatusTest {

    @Test
    public void testSuccessfulRequest() {
        given()
                .when()
                .get("https://jsonplaceholder.typicode.com/posts/1")
                .then()
                .statusCode(200); // Check for status 200
    }

    @Test
    public void testNotFoundRequest() {
        given()
                .when()
                .get("https://jsonplaceholder.typicode.com/posts/999")
                .then()
                .statusCode(404); // Check for status 404
    }
}