Python – HTTP Authentication

Authentication is the process of determining if the request has come from a valid user who has the required privileges to use the system. In the world of computer networking this is a very vital requirement as many systems keep interacting with each other and proper mechanism needs to ensure that only valid interactions happen between these programs.

The python module names requests has in-built feature to call various APIs provided by the serving web apps along with the user credentials. These credentials have to be embedded in the calling program. If the APIs verify it successfully then a valid login happens.

Installing Requests

We install the required python module named requests for running the authentication program.

pip install requests

Authenticating to Github

Below we see a simple authentication mechanism involving only the username and the password. A successful response indicates valid login.

import requests 
r = requests.get('', auth=('user', 'pass'))
print r

When we run the above program, we get the following output −


Authenticating to Twitter

We can also run a program to use twitter’s api and make a successful login by using the following code. We use the OAuth1 method available in the requests module to process the parameters required by Twitter API. As we can see the requests module is capable of handling more complex authentication mechanism involving keys and tokens rather than just the username and password mechanism.

import requests
from requests_oauthlib import OAuth1

url = ''

requests.get(url, auth=auth)

When we run the above program, we get the following output −

  "errors": [
      "code": 215,
      "message": "Bad Authentication data."

But using the proper values for OAuth1 parameters you get a successful response.