python requests session example

Python Requests Session Example

Python Requests is a popular library for making HTTP requests in Python. It provides simple and elegant API for making HTTP requests. One of the key features of Requests is Sessions. Sessions allow you to persist certain parameters across multiple requests. In this article, we will explore how to use Sessions in Python Requests library.

Creating a Session Object

To create a session object, you can simply import the requests module and call the Session() method.


import requests

# Create a session
session = requests.Session()

Making Requests with a Session Object

Once you have created a session object, you can use it to make HTTP requests. Sessions allow you to persist certain parameters across multiple requests. For example, if you need to send a specific header with all requests, you can set that header once on the session object and it will be sent with all subsequent requests.

Here's an example where we set an Authorization header using the headers property of the session object:


# Set the Authorization header on the session object
session.headers['Authorization'] = 'Bearer access_token'

# Make a GET request using the session object
response = session.get('https://api.example.com/users/123')

In this example, the Authorization header will be sent with all subsequent requests made using the session object.

Persisting Cookies Across Requests

Sessions also allow you to persist cookies across multiple requests. When you make a request using a session object, any cookies returned in the response will be stored in the session object. Those cookies will be sent with all subsequent requests made using that session object.

Here's an example where we make a GET request to a login page, then make a POST request to login using the credentials provided. The session object will store the authentication cookie returned in the response, which will be sent with all subsequent requests:


# Make a GET request to the login page
response = session.get('https://example.com/login')

# Make a POST request to login using the credentials provided
response = session.post('https://example.com/login', data={'username': 'user', 'password': 'pass'})

# The authentication cookie will be stored in the session object
# It will be sent with all subsequent requests made using this session object

Conclusion

Sessions provide a powerful and convenient way to persist certain parameters across multiple HTTP requests. They allow you to set headers, cookies, and other parameters once on the session object and have them be sent with all subsequent requests. This can help simplify your code and reduce the amount of boilerplate required for making HTTP requests.