A Comprehensive Guide to Checking HTTP Response Status Codes in Python Requests Library

Dec 04, 2025 · Programming · 11 views · 7.8

Keywords: Python | Requests Library | HTTP Status Code Checking | resp.status_code | resp.ok | raise_for_status

Abstract: This article provides an in-depth exploration of various methods for checking HTTP response status codes in the Python Requests library. It begins by analyzing common string comparison errors made by beginners, then详细介绍 the correct approach using the status_code attribute for precise status code verification. The article further examines the convenience of the resp.ok property, which automatically identifies all 2xx successful responses. Finally, by contrasting with content from Answer 2, it introduces more Pythonic exception handling approaches, including the raise_for_status() method and the EAFP programming paradigm. Complete code examples and best practice recommendations are provided to help developers write more robust network request code.

Introduction

When using Python's Requests library for HTTP requests, properly handling response status codes is crucial for ensuring application stability. Many developers, when first encountering this task, may attempt to check response status through string comparison—an approach that is not only inefficient but also error-prone. This article systematically introduces several methods for checking HTTP response status codes, from basic to advanced, helping readers establish correct programming practices.

Analysis of Common Error Patterns

A common mistake made by beginners is attempting to compare Response objects with strings. For example, in the original question, the developer tried to execute the following code:

resp = requests.post(my_endpoint_var, headers=header_var, data=post_data_var)
if resp == "<Response [200]>":
    print('OK!')
else:
    print('Boo!')

The fundamental issue with this approach is that resp is a Response object, not a string. When printing a Response object, Python calls its __str__() method, returning a string representation like <Response [200]>. However, directly comparing an object with a string will never yield equality because their types differ.

Correct Basic Checking Methods

According to the official Requests library documentation, each Response object has a status_code attribute that directly returns the integer value of the HTTP status code. This is the most straightforward method for checking specific status codes like 200:

if resp.status_code == 200:
    print('OK!')
else:
    print('Boo!')

This method is explicit and intuitive, particularly suitable for scenarios requiring exact matching of specific status codes. For instance, some APIs may use 201 to indicate successful resource creation and 200 for general success, necessitating precise checks.

Convenient Checking with resp.ok

For many application scenarios, we may only care whether the request succeeded without needing to distinguish between specific 2xx status codes. The Requests library provides the resp.ok attribute, a boolean value that is True when the status code is between 200 and 399, and False otherwise.

if resp.ok:
    print('OK!')
else:
    print('Boo!')

This approach is more concise, especially when handling all successful responses. Note that resp.ok includes not only 200 but also other success status codes like 201 and 204.

Pythonic Exception Handling Approach

Answer 2 proposes a more Pythonic approach—using the raise_for_status() method. This method is based on the "Easier to Ask for Forgiveness than Permission" (EAFP) principle.

try:
    resp = requests.post(url, headers=headers, data=data, timeout=timeout)
    resp.raise_for_status()
    # Request succeeded, continue processing response data
except requests.HTTPError as ex:
    # Handle HTTP error
    print(f'HTTP error: {ex}')
except requests.Timeout:
    # Handle timeout error
    print('Request timeout')

The raise_for_status() method raises a requests.HTTPError exception when the status code indicates an error (4xx or 5xx). The advantage of this approach is that it centralizes error handling logic in exception blocks, making the main flow clearer.

Practical Considerations

In actual development, the choice of method depends on specific requirements:

  1. Use status_code for precise control over specific status codes
  2. Use resp.ok for simply distinguishing success from failure
  3. Use raise_for_status() for more structured error handling

It's also important to note that some API designs may violate conventions. For example, some APIs might return a 200 status code even for business logic errors, with error information embedded in the response body. In such cases, merely checking the status code is insufficient, and response content parsing is also required.

Code Examples and Best Practices

Below is a complete example demonstrating how to combine multiple methods to build robust request handling logic:

import requests

def make_request(url, data=None, headers=None):
    try:
        response = requests.post(url, data=data, headers=headers, timeout=10)
        
        # Method 1: Precise status code check
        if response.status_code == 200:
            print('Exact 200 response')
        
        # Method 2: General success check
        if response.ok:
            print('Request successful')
            return response.json()  # Assuming JSON response
        else:
            # Method 3: Exception handling
            response.raise_for_status()
            
    except requests.HTTPError as e:
        print(f'HTTP error: {e}')
        # Add retry logic or error reporting here
        return None
    except requests.Timeout:
        print('Request timeout')
        return None
    except requests.RequestException as e:
        print(f'Request exception: {e}')
        return None

# Usage example
result = make_request('https://api.example.com/endpoint', 
                     data={'key': 'value'},
                     headers={'Content-Type': 'application/json'})

Conclusion

Checking HTTP response status codes is a fundamental yet important aspect of network programming. By avoiding the error-prone pattern of string comparison and instead using the specialized attributes and methods provided by the Requests library, developers can write more reliable and maintainable code. status_code offers precise control, resp.ok provides convenient checking, and raise_for_status() delivers exception handling aligned with Python philosophy. In practical development, appropriate methods should be selected based on specific needs, while considering API-specific behaviors to ensure application robustness.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.