API Navigator Logo

Using Sessions in Python Requests

Author: Newtum

This guide explains how to use Session objects in the Python Requests library to persist parameters and cookies across multiple requests to the same host.

What is a Session Object?

A Session object allows you to persist certain parameters across requests. It also persists cookies, which is useful for maintaining a logged-in state. When you make multiple requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase.

Example of a Session

Here's how to create a session and make requests with it. Notice that cookies set by the first request are automatically sent in the second request.

import requests

# Create a session object
s = requests.Session()

# The first request to set a cookie
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')

# The second request will automatically have the cookie
response = s.get('https://httpbin.org/cookies')

print(response.text)
# The output will show that 'sessioncookie' was sent back

Persisting Parameters

You can also set default headers or query parameters for all requests made with a session.

import requests

s = requests.Session()
s.headers.update({'x-test-header': 'true'})
s.params.update({'api_key': 'your_api_key'})

# This request will have both the header and the query parameter
response = s.get('https://httpbin.org/get')

print(response.json()['headers']['X-Test-Header'])
print(response.json()['args']['api_key'])