All Courses

Http Authentication In Python

Shashank Shanu

3 years ago

Http Authentication In Python | insideAIML
Table of Contents
  • What is Authentication?
  • How to install Requests package?
  • How to Authenticate GitHub?
  • How to Authenticate Twitter?

What is Authentication?

       The process of determining if the request has come from a valid user who has the required permission to the system is known as Authentication.
It’s a very important requirement as in the world of computer networking many systems keep interacting with each other and the proper mechanism needs to ensure that only valid interactions happen between these programs.
Python has a module name requests which comes with a built-in feature to call different APIs provided by the serving web apps along with user credentials. These credentials have to be embedded in the calling program. So, if the APIs verify it successfully then it gets a valid login.

How to install Requests package?

     To install python-requests module for Authentication run the below-mentioned command.
pip install requests

How to Authenticate GitHub?

        We can authenticate to GitHub very simply using the username and the password. If authentication is successful, we will receive a valid login response.
Run the below command to authenticate-
import requests 
req = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print(req)

How to Authenticate Twitter?

        Python provides us a way where we can run a program in it to use twitter’s API and successfully log in to a twitter account.
Here we use the OAuth1 method available in the requests module to the parameters required by the Twitter API. Python request module is capable of handling more complex authentication mechanism involving keys and tokens rather than just the username and password mechanism.
import requests
from requests_oauthlib import OAuth1

url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
              'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')

requests.get(url, auth=auth)
The output of the above program-
{
  "errors": [
    {
      "code": 215,
      "message": "Bad Authentication data."
    }
  ]
}
         As we see we received an error message. But using the proper values for OAuth1 parameters we will get a successful response.
I hope you enjoyed reading this article and finally, you came to know about Http Authentication In Python.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…

Submit Review