The requests.Session
class in Python’s requests
module allows you to persist certain parameters across multiple requests. It helps to maintain cookies, headers, and connection pooling for better performance and convenience when making multiple requests to the same host.
Table of Contents
- Introduction
requests.Session
Class Syntax- Examples
- Basic Usage
- Persisting Headers
- Maintaining Cookies
- Session with Authentication
- Handling JSON Responses
- Real-World Use Case
- Conclusion
Introduction
The requests.Session
class is part of the requests
module, which makes it easy to make HTTP requests in Python. Using a session object, you can persist certain parameters across requests, such as headers and cookies, which can be useful when interacting with web services that require stateful interactions.
requests.Session Class Syntax
Here’s how you use the requests.Session
class:
import requests
session = requests.Session()
response = session.request(method, url, **kwargs)
Common Methods:
session.get(url, **kwargs)
session.post(url, **kwargs)
session.put(url, **kwargs)
session.delete(url, **kwargs)
session.head(url, **kwargs)
session.options(url, **kwargs)
session.patch(url, **kwargs)
Parameters:
url
: The URL for the request.**kwargs
: Optional arguments to customize the request.
Returns:
- A
Response
object containing the server’s response to the HTTP request.
Examples
Basic Usage
Create a session and send a GET request.
import requests
session = requests.Session()
response = session.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.json())
Output:
{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'}
Persisting Headers
Persist headers across multiple requests using a session.
import requests
session = requests.Session()
session.headers.update({'Authorization': 'Bearer your_token'})
response = session.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.json())
response = session.get('https://jsonplaceholder.typicode.com/posts/2')
print(response.json())
Output:
{'userId': 1, 'id': 1, 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'}
{'userId': 1, 'id': 2, 'title': 'qui est esse', 'body': 'est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla'}
Maintaining Cookies
Maintain cookies across multiple requests.
import requests
session = requests.Session()
session.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
response = session.get('https://httpbin.org/cookies')
print(response.json())
Output:
{'cookies': {'sessioncookie': '123456789'}}
Session with Authentication
Use a session with authentication.
import requests
session = requests.Session()
session.auth = ('user', 'pass')
response = session.get('https://httpbin.org/basic-auth/user/pass')
print(response.json())
Output:
{'authenticated': True, 'user': 'user'}
Handling JSON Responses
Send a POST request with JSON data and handle the JSON response.
import requests
session = requests.Session()
json_data = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = session.post('https://jsonplaceholder.typicode.com/posts', json=json_data)
print(response.json())
Output:
{'title': 'foo', 'body': 'bar', 'userId': 1, 'id': 101}
Real-World Use Case
Making Multiple Requests to an API
Use a session to make multiple requests to an API that requires authentication and maintain state across requests.
import requests
session = requests.Session()
session.headers.update({'Authorization': 'Bearer your_token'})
# Get user data
response = session.get('https://jsonplaceholder.typicode.com/users/1')
user_data = response.json()
print(user_data)
# Post a new post as the user
json_data = {'title': 'foo', 'body': 'bar', 'userId': user_data['id']}
response = session.post('https://jsonplaceholder.typicode.com/posts', json=json_data)
print(response.json())
Output:
{'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.biz', 'address': {'street': 'Kulas Light', 'suite': 'Apt. 556', 'city': 'Gwenborough', 'zipcode': '92998-3874', 'geo': {'lat': '-37.3159', 'lng': '81.1496'}}, 'phone': '1-770-736-8031 x56442', 'website': 'hildegard.org', 'company': {'name': 'Romaguera-Crona', 'catchPhrase': 'Multi-layered client-server neural-net', 'bs': 'harness real-time e-markets'}}
{'title': 'foo', 'body': 'bar', 'userId': 1, 'id': 101}
Conclusion
The requests.Session
class is used for making HTTP requests in Python. It allows you to persist headers, cookies, and other parameters across multiple requests, which can simplify your code and improve performance when interacting with web services and APIs.