Sling Academy
Home/Python/Python Requests module: Print response status code and headers

Python Requests module: Print response status code and headers

Last updated: January 02, 2024

Introduction

The Python requests module is a popular HTTP library used for making API calls, fetching web content, and more. Understanding how to print and interpret status codes and headers can be crucial for debugging and ensuring that your requests are successful.

Getting Started with the Requests Module

Before diving into the details, it’s important to have the requests module installed. You can install it using pip:

pip install requests

Let’s start with a simple GET request:

import requests

response = requests.get('https://api.example.com/data')
print('Status Code:', response.status_code)

The status_code property of the response object gives you the HTTP status code of the request.

More about HTTP Status Codes

HTTP status codes indicate the outcome of your request. They are divided into several classes:

  • 1xx: Informational
  • 2xx: Success
  • 3xx: Redirection
  • 4xx: Client Errors
  • 5xx: Server Errors

For example, a status code of 200 indicates success, while 404 indicates that the requested resource was not found.

Printing Headers

Headers contain metadata about the request and response. To print them, simply access the headers attribute on the response object:

print('Headers:', response.headers)

This will output a dictionary-like object of the headers.

Advanced Use Cases

When making more complex requests, you may need to handle redirects, cookies, or custom headers. Here’s how to manage redirects and to check final URL:

response = requests.get('https://api.example.com/redirect', allow_redirects=True)
print('Final URL:', response.url)

For handling cookies:

cookies = dict(session='12345')
response = requests.get('https://api.example.com/data', cookies=cookies)
print('Cookies:', response.cookies)

To send custom headers with your request:

headers = {'Accept': 'application/json'}
response = requests.get('https://api.example.com/data', headers=headers)

Inspecting headers can be particularly useful in these scenarios, to ensure that the server is receiving the correct information.

Error Handling

Handling errors properly is crucial. Inspect the status_code and use response.raise_for_status() to raise an HTTPError if the request returned an unsuccessful status code.

try:
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(f'HTTP Error: {e}')

Knowing how to read status_code and headers helps you debug these errors more effectively.

Working with Sessions

Sessions allow you to persist certain parameters across requests. For example, if you need to maintain a set of cookies:

with requests.Session() as session:
    session.headers.update({'Accept': 'application/json'})
    response = session.get('https://api.example.com/protected-data')
    print('Status Code:', response.status_code)
    print('Headers:', response.headers)

Session objects respect all aspects of the request, including cookies and headers, and can be used to make repeated calls more efficiently.

Conclusion

Being able to print and understand the status code and headers of HTTP responses is a fundamental skill for developers working with APIs. The Python requests module provides a user-friendly way to execute these tasks. By incorporating best practices and error handling into your code, you can ensure your applications communicate effectively with web services and handle unexpected scenarios gracefully.

Next Article: Python Requests module: Tracking redirection and history

Previous Article: Python Requests Module: Exception Handling Best Practices

Series: Python: Network & JSON tutorials

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types