Authentication with Requests
When working with APIs, authentication is often required to access protected resources. Python’s Requests library makes it simple to handle various authentication mechanisms like Basic authentication, token-based authentication, and OAuth.
Basic Authentication
Basic authentication involves sending a username and password with each request. The Requests library provides built-in support for this.
Example: Basic Authentication
import requests
url = "https://httpbin.org/basic-auth/user/passwd"
response = requests.get(url, auth=("user", "passwd"))
if response.status_code == 200:
print("Authentication Successful")
else:
print("Authentication Failed")
Token-Based Authentication
Token-based authentication uses a secure token in the headers to verify requests. This is common in modern APIs.
Example: Token-Based Authentication
url = "https://api.example.com/data"
headers = {
"Authorization": "Bearer YOUR_ACCESS_TOKEN"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
print("Data:", response.json())
else:
print("Authentication Failed")
OAuth Authentication
OAuth is a more complex and secure method for authentication. It allows access without sharing a username and password directly.
Example: OAuth with requests-oauthlib
Install the requests-oauthlib
library:
pip install requests-oauthlib
Code Example:
from requests_oauthlib import OAuth1
import requests
# OAuth1 credentials
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
oauth = OAuth1(
"YOUR_CONSUMER_KEY",
"YOUR_CONSUMER_SECRET",
"YOUR_ACCESS_TOKEN",
"YOUR_ACCESS_SECRET"
)
response = requests.get(url, auth=oauth)
if response.status_code == 200:
print("Data:", response.json())
else:
print("Authentication Failed")
Try It Yourself
Problem 1: Basic Authentication
Access the URL https://httpbin.org/basic-auth/test/test
using basic authentication with username test
and password test
. Print the response status.
Show Solution
import requests
url = "https://httpbin.org/basic-auth/test/test"
response = requests.get(url, auth=("test", "test"))
if response.status_code == 200:
print("Authentication Successful")
else:
print("Authentication Failed")
Problem 2: Token-Based Authentication
Access the URL https://api.example.com/private
with the token "123456abcdef"
. Print the response JSON.
Show Solution
import requests
url = "https://api.example.com/private"
headers = {
"Authorization": "Bearer 123456abcdef"
}
response = requests.get(url, headers=headers)
print("Response JSON:", response.json())
Authentication is a vital part of API usage. With Requests, you can easily handle various methods, from Basic to OAuth (Open Authorization). Practice these techniques to securely interact with APIs!