Sobes.tech
Junior
241

How does a client determine if a request was successful?

Answer from AI

sobes.tech AI

The client can determine the success of a request by the following signs:

  • HTTP Status Code: The most reliable method. Codes in the range from 200 to 299 (e.g., 200 OK, 201 Created, 204 No Content) indicate successful execution of the request. Codes 4xx (client errors) and 5xx (server errors) indicate failure.
  • Response Body: A successful response may contain the expected payload (e.g., JSON data, XML, HTML). Absence or unexpected content may indicate a problem, even with a successful status code.
  • Response Headers: Some headers (e.g., Content-Type, Content-Length) can confirm the type and size of the received data.
  • Exception Handling: On the client side, network errors or timeouts will raise exceptions that should be handled.

Example of checking the status code in Python using the requests library:

import requests

try:
    response = requests.get("https://api.example.com/data")

    # Check HTTP status code
    if 200 <= response.status_code < 300:
        print("Request successful.")
        # You can parse response.json() or response.text
    else:
        print(f"Request finished with error: {response.status_code}")
        # Handle 4xx and 5xx errors

except requests.exceptions.RequestException as e:
    # Handle network errors (e.g., timeout, connection error)
    print(f"Error during request: {e}")

Summary table of HTTP status codes:

Range Description Example
1xx Informational 100 Continue
2xx Success 200 OK
3xx Redirection 301 Moved Permanently
4xx Client Error 404 Not Found
5xx Server Error 500 Internal Server Error