This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Sessions

It can be tedious having to enter your username and password over and over every time to make a request.

This is where Sessions come in handy. It offers a persistent connection to the server. You can log in once and then keep the same connection for your remaining requests.

The Session object offers the same get, put, etc. methods as earlier.

with requests.Session() as session:
    session.auth = ("username", getpass())
    response = session.get("https://api.github.com/user")
    second_response = session.get("https://api.github.com/user")

Another example from our search query earlier. We can use sessions to “remember” the parameters, and reuse them for another request (perhaps we want to retrieve the search results for Page 2).

with requests.Session() as session:
    session.params.update({"q": "requests+language:python"})
    session.params.update({"per_page": 10})
    response = session.get("https://api.github.com/search/repositories")
    print(response.url)
    ## https://api.github.com/search/repositories?q=requests%2Blanguage%3Apython&per_page=10

    response = session.get("https://api.github.com/search/repositories", params={"page": 2})
    print(response.url)
    ## https://api.github.com/search/repositories?q=requests%2Blanguage%3Apython&per_page=10&page=2

    response = session.get("https://api.github.com/search/repositories", params={"page": 3})
    print(response.url)
    ## https://api.github.com/search/repositories?q=requests%2Blanguage%3Apython&per_page=10&page=3

Yet another example: we can try to store some cookies across different requests. We are using yet another API service for testing purposes https://httpbin.org/.

with requests.Session() as session:
    session.get("https://httpbin.org/cookies/set/cookiename1/123")
    session.get("https://httpbin.org/cookies/set/cookiename2/999")
    response = session.get("https://httpbin.org/cookies")
    print(response.json())
    ## {'cookies': {'cookiename1': '123', 'cookiename2': '999'}}

Of course, some people may argue that using Sessions/cookies breaks the statelessness constraint of REST APIs (each request must be independent and self-sufficient). We will not go into this debate - sometimes you need to compromise!