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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots