Advertisements

How to send an HTTP request to a HTTP Basic Authentication endpoint in Python 3 with requests library

When you are building a Python 3 application for the Internet, you could encounter API endpoints that use HTTP Basic Authentication as the authentication mechanism.

In such a situation, using the requests library in your Python 3 code makes it easier to communicate with those endpoints.

In case you need to build a Python 3 application that sends HTTP request to a HTTP Basic Authentication endpoint, this is how you can do so with the requests library.

How to construct a HTTP request to an endpoint with HTTP Basic Authentication in Python 3

When you want to construct a HTTP request to an endpoint with HTTP Basic Authentication from scratch, there are several procedures to follow. Therefore, the creators of the requests library had made it easy for us to construct a HTTP request to an endpoint with HTTP Basic Authentication easily.

With the requests library, we can either encapsulate the username and password pair in an instance of requests.auth.HTTPBasicAuth or in a tuple:

basicAuthCredentials = HTTPBasicAuth('username', 'password')
# Or
basicAuthCredentials = ('username', 'password')

After we had done so, we then pass in basicAuthCredentials as the value to the auth parameter inside one of the following functions:

Python 3 example for sending a HTTP GET request to a HTTP Basic Authentication endpoint with the request library

For example, if we want to send a HTTP GET request to a HTTP Basic Authentication endpoint, we can write Python 3 codes similar to the following:

import requests
#
basicAuthCredentials = ('username', 'password')

# Send HTTP GET request to server and attempt to receive a response
response = requests.get('http://httpbin.org/basic-auth/username/password', auth=basicAuthCredentials)
     
# If the HTTP GET request can be served
if response.status_code == 200:
    print(response.text)

After the above set of codes is run, you should see the following output in your terminal:

{
  "authenticated": true, 
  "user": "user"
}
Advertisements

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.

Advertisements
Advertisements

Udemy.com Homepage 300x250 Domain names for just 88 cents!

Find a domain starting at $0.88

powered by Namecheap