This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Advanced topics

Authentication

You will often need to provide user authentication to use some parts of a Web API. For example, my example blog API allows a user to retrieve his/her details, but only when they are signed in.

>>> response = requests.get("http://localhost:5000/user")
>>> print(response.status_code)  # Unauthorized
401

A Web API can implement authentication in many different ways. The simplest and most common authentication method provided by HTTP is the HTTP Basic Authentication. This method includes the username and password provided by the user into an "Authorization" header in the HTTP request, encoded in a simple way (see Wikipedia link above).

The requests package gives an easy way to provide user credentials to the Web API, using the auth keyword argument. It accepts a different number of authentication protocols, including HTTP Basic Authentication by default.

>>> username = "cobra"
>>> password = "hiss"
>>> response = requests.get("http://localhost:5000/user", auth=(username, password))
>>> print(response.status_code)
200
>>> print(response.json())
{'email': 'jar.fowler@example.com', 'id': 1, 'name': 'Jar Fowler', 'user': 'cobra'}
>>> print(response.request.headers)
{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 
 'Connection': 'keep-alive', 'Authorization': 'Basic Y29icmE6aGlzcw=='}

Note how the request headers (last line) contain the “Authorization” header with an encoded version of the username and password included.

You can also test using an invalid username/password. Other users I have on the blog API include ("nagini", "crawl"), ("viper", "bite"), and ("anaconda", "slither").

>>> response = requests.get("http://localhost:5000/user", auth=("cobra", "meow"))
>>> print(response.status_code)
401
>>> print(response.json())
{}

See the documentation for some other authentication protocols. We will not cover any further authentication methods.

Use getpass.getpass() to allow your user to enter passwords without displaying them on the terminal.

>>> from getpass import getpass
>>> password = getpass()
Password:
>>> print(password)
ThePasswordIJustTyped