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,
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.
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())
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())
For requests made with valid Basic Auth credentials
200 {'authenticated': True}
For requests made with invalid Basic Auth credentials
401 {'authenticated': False}
Quick Links
Legal Information
Social Media