Managing Sessions in Requests

When making multiple requests to the same server, using session objects helps maintain persistent settings, such as cookies and headers. This reduces redundancy and improves efficiency.


Why Use Session Objects?

  • Persistent Cookies: Automatically manages cookies for requests and responses.
  • Shared Headers: Headers set once can be reused across multiple requests.
  • Connection Persistence: Maintains connections to the server for efficiency.

Using Session Objects

Example: Persistent Sessions

import requests
 
# Create a session object
session = requests.Session()
 
# Set common headers
session.headers.update({"User-Agent": "MyApp/1.0"})
 
# First request
response1 = session.get("https://httpbin.org/cookies/set?name=value")
print("Response 1 Cookies:", session.cookies.get_dict())
 
# Second request
response2 = session.get("https://httpbin.org/cookies")
print("Response 2 Cookies:", response2.json())

Output

Response 1 Cookies: {'name': 'value'}
Response 2 Cookies: {'cookies': {'name': 'value'}}

Sharing Cookies and Headers

Cookies and headers set in one request can be reused in subsequent requests.

Example: Sharing Headers Across Requests

# Create a session object
session = requests.Session()
 
# Set headers
session.headers.update({
    "Authorization": "Bearer YOUR_ACCESS_TOKEN",
    "Content-Type": "application/json"
})
 
# First request
response1 = session.get("https://httpbin.org/headers")
print("Response 1 Headers:", response1.json()["headers"])
 
# Second request
response2 = session.post("https://httpbin.org/post", json={"key": "value"})
print("Response 2 JSON:", response2.json()["json"])

Managing Cookies

Example: Manually Adding Cookies

# Create a session object
session = requests.Session()
 
# Add a cookie manually
session.cookies.set("sessionid", "12345")
 
# Send a request
response = session.get("https://httpbin.org/cookies")
print("Cookies Sent:", response.json())

Try It Yourself

Problem 1: Persistent Sessions

Create a session and perform two requests to https://httpbin.org/cookies:

  1. Set a cookie.
  2. Retrieve all cookies.
Show Solution
import requests
 
session = requests.Session()
 
# Set a cookie
session.get("https://httpbin.org/cookies/set?user=testuser")
 
# Retrieve all cookies
response = session.get("https://httpbin.org/cookies")
print("Cookies:", response.json())

Problem 2: Shared Headers

Create a session with a common header and send two requests:

  1. A GET request to https://httpbin.org/headers.
  2. A POST request to https://httpbin.org/post with a JSON payload.
Show Solution
import requests
 
session = requests.Session()
session.headers.update({"Authorization": "Bearer YOUR_ACCESS_TOKEN"})
 
# GET request
response1 = session.get("https://httpbin.org/headers")
print("Headers Sent:", response1.json()["headers"])
 
# POST request
response2 = session.post("https://httpbin.org/post", json={"key": "value"})
print("POST Response JSON:", response2.json()["json"])

Using session objects in Requests simplifies repetitive tasks and improves performance when interacting with APIs or web services. Experiment with session features to streamline your Python applications!