An authentication token is a piece of data, often a string, that is used to represent the authenticated user. Instead of sending the username and password with each request, a token is sent, usually in the request headers.
Prerequisite:
- Python is installed on the machine
- PIP is installed on the machine
- PyCharm or other Python Editor is installed on the machine
If you need help in installing Python, please refer to this tutorial – How to Install Python on Windows 11.
If you need help in installing PyCharms, please refer to this tutorial – How to install PyCharms on Windows 11.
The syntax for basic authentication in Python Request is
headers = {'Authorization': 'Basic dXNlcjpwYXNz'}
![](https://qaautomation.expert/wp-content/uploads/2024/01/image-113.png?w=845)
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 auth param and the get() method in requests will take care of the basic authorization for us.
Below is the example of basic authentication token.
import requests
endpoint = 'https://httpbin.org/basic-auth/user/pass'
token = 'Basic dXNlcjpwYXNz'
def test_auth_token():
headers = {'Authorization': token}
response = requests.get(endpoint, headers=headers)
response_body = response.json()
print(response_body)
assert response.status_code == 200
assert response_body["authenticated"] == True
assert response_body["user"] == "user"
Save above file as Authentication_test.py and run using the below command:
pytest Authentication_test.py -s
Note: -s is shortcut for –capture=no
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2024/01/image-114.png?w=1026)
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!