Today, all applications require APIs for storing databases, fetching external information, or for authentication purposes. You must have dealt with this word before while developing applications in Python. Here, we will discuss how to make API calls using Bearer Token Authentication.
Also Read: Harnessing the Power of AI: Python Notebooks for Big Data Analysis in Sigma
Bearer Token Authentication is a method of authenticating API requests by including a token in the request headers. It simplifies the authentication process by eliminating the need to send credentials with every request. To use Bearer Token Authentication, first obtain a token from the API provider by exchanging your client credentials through an authentication protocol like OAuth 2.0. Then, include the token in the ‘Authorization’ header of your API requests
Understanding Bearer Token Authentication
Bearer Token authentication is a type of authentication that includes sending a token with each API request. It is important for the application as it authenticates the user and allows us to access data from the backend. If you have worked with APIs, you must have used the traditional API method that required sending credentials with each request. But in Bearer Token Authentication, we will send the token that can simplify the whole process.
Also Read: Analyze Weather Data with Python And A Weather API To Predict Weather Trends
Obtaining a Bearer Token
Before making API calls, you must obtain a token from the API provider. First, set up the application with the API provider and obtain all the credentials, such as client ID and client secret. Next, exchange your credentials for the bearer token using the OAuth 2.0 authentication protocol or other specified methods.
Making API Calls with Bearer Token in Python
Once you have obtained the token, you can start making API calls in Python.
Install Necessary Libraries
First, we will install the ‘requests’ library. This requests library is commonly used for making HTTP requests in Python, so it should be imported into the source code. Add the following code to the terminal or command prompt.
pip3 install requests
Import Libraries
Secondly, we will import the requests library in your Python script.
import requests
Constructing the API Request
Now, we will create an API request with the appropriate HTTP method, URL, headers, and payload.
url = 'https://api.example.com/resource'
headers = {
'Authorization': 'Bearer YOUR_BEARER_TOKEN',
'Content-Type': 'application/json'
}
response = requests.get(url, headers=headers)
Here, I have taken a sample API link from ‘URL.’ Add your bearer token instead of “YOUR_BEARER_TOKEN” inside the ‘headers’. At last, we create a response that fetches data by sending the GET request ( URL and header).
Handling API Responses with Bearer Token
Now depending on the application, handle your responses well. You can also call other parameters like status code, content etc.
if response.status_code == 200:
data = response.json()
else:
print('Error:', response.status_code)
Here we are checking the status code. If the status code equals 200, it means that the data fetching was successful. Thus inside the if block, you must add the logic to process the API response data. After receiving data in JSON format, you can try converting it into an Integer or other data type. The code will print the error inside the other block if any error occurs when fetching data.
Example: GET Request with Bearer Token
Here, I will show you how to make a simple GET request using a Bearer Token. This will help you shape code for other types of requests, such as POST, etc.
Let’s take a sample API like TMDB, which provides recommendations for movies, TV shows, etc. First, create your login into the TMDB and get the Bearer Token Key in the API section. Secondly, we will request the endpoint ( genre/movie/list) to get the list of genres supported by TMDB. For reference, I am also providing the official link to TMDB which is (“https://developer.themoviedb.org/docs/getting-started”).
import requests
url = "https://api.themoviedb.org/3/genre/movie/list?language=en"
headers = {
"accept": "application/json",
"Authorization": "Bearer_Token"
}
response = requests.get(url, headers=headers)
print(response.text)
Here you must add your Bearer Token Key in place of “Bearer_Token”. Next, the response will fetch the data by GET request containing the header and URL. Lastly, we will print the data to check whether it works. As we can refer to the response, we have different genres with their respective genre_ids. This way we can fetch data from any API endpoint using the GET request method.
How can we convert the API credentials into Bearer Token?
First, to convert API credentials, authenticate the application with OAuth 2.0 or a similar authentication mechanism. Send your client credentials in exchange for a bearer token.
What different methods can we use with Bearer Token Authentication?
We can use different HTTP methods, such as GET, POST, PUT, and DELETE, to process data coming from the API. The Bearer Token is just how the client authenticates itself from the server. Rest, it performs similarly to traditional methods.
Summary
Bearer Token is a more secure and easiest approach to authenticate users from the server. First, obtain the Bearer Token from the API provider to make API calls with Bearer Token. Next, create API requests using different HTTP methods like GET, POST, and more. Lastly, after receiving a response, handle the data as per the application’s needs.