HomeContact
Python
Basic Auth with python requests.
Karthikeya
February 27, 2021
1 min

Basic Auth is one of the many HTTP authorization technique used to validate access to a HTTP endpoint. Understanding Basic Auth is very simple, the user requesting the access to an endpoint has to provide either,

  • Username and password as credentials in the API call (or)
  • Basic authorization token as credentials in the request header

Let us explore both the ways in python. For the purpose of demo, we will be using basic auth end point exposed by postman

https://postman-echo.com/basic-auth

Although this is a GET request, Basic Auth calls for all the other HTTP methods will remain the same with an exception that instead of get() method, use corrosponding method exposed by requests library.

1. USERNAME & PASSWORD AS CREDENTIALS:

We can directly embed basic auth username and password in the request by passing username and password as a tuple to the auth param and the get() method in requests will take care of the basic authorization for us.

import requests

url = "https://postman-echo.com/basic-auth"
username = "postman"
password = "password"

response = requests.get(url, auth=(username, password))
print(response.status_code)
print(response.json())

2. BASIC AUTH TOKEN AS CREDENTIALS:

There is a chance that for an API, you receive only the basic auth token instead of username and password. In this scenario, all you need to do is to embed the basic auth token as Authorization header while making the API call. A sample basic auth token would look like this

Basic cG9zdG1hbjpwYXNzd29yZA==
import requests

url = "https://postman-echo.com/basic-auth"
header = {"Authorization" : "Basic cG9zdG1hbjpwYXNzd29yZA=="}

response = requests.get(url, headers=header)
print(response.status_code)
print(response.json())

OUTPUT

For requests made with valid Basic Auth credentials

200
{'authenticated': True}

For requests made with invalid Basic Auth credentials

401
{'authenticated': False}

Related Posts

Deep comparison of JSON in python
November 18, 2021
1 min
© 2021, All Rights Reserved.

Quick Links

About UsContact UsSite Map

Social Media