Handling basic authentication using requests in Python

Handling basic authentication using requests in Python

An authentication that allows end users to access the application or API using a simple username and password is called basic authentication.

In the below example, I am trying to authenticate the API https://postman-echo.com/basic-auth with username=’postman’ and password=’password’.

And verifying that on a successful attempt, the status code should be ‘200’.

import requests

BASE_URI = "https://postman-echo.com/basic-auth"
credentials = ('postman', 'password') # username and password as a tuple

def test_basic_auth():
    '''testing basic auth using '''
    response = requests.get(BASE_URI, auth=credentials)
    status = response.status_code
    print(f"\nStatus Code is {status}")
    if status == 200:
        print("Authentication successful")
    else:
        print("Authentication failed")

As shown in the above code snippet, we created a tuple ‘credentials’ and passed it to the get() method as an argument.

Upon executing the test, the output is as below.

platform linux -- Python 3.10.12, pytest-7.4.0, pluggy-1.2.0 -- /usr/bin/python3.10
cachedir: .pytest_cache
rootdir: /home/brahma/api/api-testing-python
plugins: Faker-19.6.2
collected 1 item                                                                                                                         

authentication/test_basic_authentication.py::TestBasicAuthentication::test_ba_usr_pwd 
Status Code is 200
Authentication successful
PASSED

In some cases, instead of a username and password, we will be provided with an access token. In such cases, we have to add the token to the request header and pass it to the http method as shown below.

Basic cG9zdG1hbjpwYXNzd29yZA==

After adding the given access token to the header and passing it to the method the test looks like this.

BASE_URI = "https://postman-echo.com/basic-auth"
header ={
    'Content-Type': 'application/json',
    'Authorization': 'Basic cG9zdG1hbjpwYXNzd29yZA=='
}

def test_basic_auth_using_token():
    '''testing basic auth using '''
    response = requests.get(BASE_URI, headers=header)
    print(response.text)
    status = response.status_code
    print(f"\nStatus Code is {status}")
    if status == 200:
        print("Authentication successful")
    else:
        print("Authentication failed")

In this way, we can handle the basic authentication using the requests module in Python. Thanks for reading.

#Python #Pytest #Requets #Programming #apitesting

Did you find this article valuable?

Support Brahma Rao Kothapalli by becoming a sponsor. Any amount is appreciated!