API Navigator Logo

Handling the Response in Python Requests

Author: Newtum

This guide explores the `Response` object that is returned after making a request with the Python Requests library. We will look at accessing the status code, headers, and body of the response.

The Response Object

When you make a request, Requests returns a `Response` object. This object contains all the information sent back by the server.

import requests

response = requests.get('https://api.github.com')
print(type(response))

Status Code

The `status_code` attribute gives you the HTTP status code. You can use this to check if the request was successful (e.g., 200 OK).

import requests

response = requests.get('https://api.github.com')
print(f"Status Code: {response.status_code}")

if response.status_code == 200:
    print("Request was successful.")
elif response.status_code == 404:
    print("Resource not found.")

Response Headers

The `headers` attribute is a dictionary-like object containing the response headers.

import requests

response = requests.get('https://api.github.com')
print("Response Headers:")
for key, value in response.headers.items():
    print(f"  {key}: {value}")

print("\nContent-Type:", response.headers['Content-Type'])

Response Body

You can access the response body in different ways: `.text` for text content (decoded), `.content` for raw binary content, and `.json()` to parse JSON.

import requests

response = requests.get('https://jsonplaceholder.typicode.com/todos/1')

# Get the body as text
print("Text Body:", response.text)

# Get the body as raw bytes
print("Content (bytes):", response.content)

# Decode the body as JSON
print("JSON Body:", response.json())