This tutorial’s main aim and function are to describe how to hide an API key within the context of the COVID-19 data API. Let’s look at a step-by-step guide on connecting to the COVID-19 data API, retrieving data from the API, hiding the API key, and accessing the API with the hidden API key.
Getting an API Key
The COVID-19 data API is a Freemium API in that it includes a free tier (part of the Basic plan) that we can use to test the code that fetches data from the API endpoints within the specified limitations.
Let’s look at the mechanisms or steps required to connect to the COVID-19 data API and how to receive data from this API.
First off, you have to get an API key. Before we discuss where to find this key, let’s look at a brief definition of an API key:
An API key is a code that gets passed between software applications and the API. It aims to identify the user, developer, or calling program, to prevent abuse or malicious use of the associated API. It acts as a unique identifier and a secret authentication token. The API key is partnered with a set of access rights that are only applicable to the associated API.
It is found on the API documentation page that allows you to test the exposed endpoints.
Initializing, connecting, and sending requests to the COVID-19 API
As a means to demonstrate how to initialize, connect, and send requests to the COVID-19 API, let’s use the getLatestTotals endpoint as an example.
import os import requests from requests.exceptions import HTTPError #retrieve API key from environment variables api_key = os.environ.get('COVID_API_KEY') #initialize url, query string, and headers url = "https://covid-19-data.p.rapidapi.com/totals" qrystr = {'format':"json"} hdrs = { 'x-rapidapi-host': "covid-19-data.p.rapidapi.com", 'x-rapidapi-key': api_key } #call the API endpoint - Use try/except to catch errors try: response = requests.request("GET", url, headers=hdrs, params=qrystr) response.raise_for_status() #access json content response_data = response.json() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}')
Note: The try/except pattern is used to pick up on any errors that occur when requesting data from the API. This is not mandatory but is an effective way of handling any errors and closing the program properly without it “blowing up.”
Receiving data from the COVID-19 API
The getLatestTotals endpoint returns the following information:
- The confirmed number of COVID-19 cases
- Number of critical cases
- Number of fatalities (deaths)
- Number of recoveries
- Date time stamp for last changed date
- Date time stamp for last updated date
Here is a code sample that demonstrates how to retrieve the data from the JSON response object. You’ll notice that the assignment statements, assigning each value of a key to an independent variable, are inside the try/except block. This ensures that the JSON object’s data is not assigned if there is an HTTP error or other exception.
#call the API endpoint - Use try/except to catch errors try: response = requests.request("GET", url, headers=hdrs, params=qrystr) response.raise_for_status() #access json content response_data = response.json() #retrieve the variables from the json response object confirmed = int(response_data.get('confirmed')) critical = int(response_data.get('critical')) deaths = int(response_data.get('deaths')) str_last_change = response_data.get('lastChange') str_last_update = response_data.get('lastUpdate') recovered = int(response_data.get('recovered')) except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}')
How to hide an API Key
Because an API key is a unique identifier and a secret authentication token, it’s not a good idea to add it to the top of your Python script in an exposed format like in this example:
#initialize url, query string, and headers url = "https://covid-19-data.p.rapidapi.com/totals" qrystr = {'format':"json"} hdrs = { 'x-rapidapi-host': "covid-19-data.p.rapidapi.com", 'x-rapidapi-key': "<your rapidAPI unique key>" }
Therefore, let’s consider hiding your API key in environment variables or binary files.
Note: These options are operating system dependent. So, we’ll first look at how to hide the API key in a Windows OS and then the Mac OS / Linux OS.
1. Environment Variables
The Windows OS environment variables are created by navigating to the Control Panel, System and Security, System, and Advanced System Settings. When this menu has opened, there is an <Environment Variables> button on the bottom right.
Click on the <Environment Variables> button, and the following screen will open, allowing you to add both system variables and user variables.
It is not necessary to add the API key to a system variable. A user variable is sufficient.
Click on the top <New> button indicated by the red arrow in this screenshot. The following dialog box will open.
Give the variable a descriptive name like “COVID_API_KEY.” And then, copy the API key found in the section above titled, “Where can I find the COVID-19 API?” into the edit box titled “Variable value.”
Click on the <OK> button to save the variable.
The Mac OS / Linux OS environment variables are created as follows:
- A file called .bash_profile must be modified.
- To do this, you first need to open up a new Terminal window.
- To navigate to your home directory, type cd <enter>.
- The next step is to open the file using a text editor like nano.
- To do this, you type nano .bash_profile
- Then add the environment variable, as shown in the example.
- Save and quit out of nano and the terminal.
export COVID_API_KEY="your_rapidAPI_unique_key"
2. Binary Files
The best way to create a binary file is by writing a Python script that hides your API key in a binary file.
Note: The script that creates the binary file should not be packaged with the software because the API key is exposed in this script. No matter how you hide the key in the final software package, there is always a chance that a hacker will find the key.
Here is an example of how to create a binary config file using a python script.
import io #initialize string strApiKey = "your rapidAPI unique key" #open file as a binary file f = open('api_file.bin', 'wb') #convert string to bytes strBytes = strApiKey.encode() #write byte string to binary file f.write(strBytes) f.close()
Essentially, you copy the API key into this script and run it once. Once the binary file has been created, you can access it in the Python scripts you use to access the API’s endpoints.
Calling the API with a hidden API key
Because there are two ways to hide an API key, there are also two ways to retrieve it.
1. Environment variables
This is the simplest way to store and to retrieve a hidden API key. Here is an example:
import os api_key = os.environ.get('COVID_API_KEY')
Here is a copy of this code added to the original script. The api_key variable is used to populate the HDRS dictionary.
import os import requests from requests.exceptions import HTTPError #retrieve API key from environment variables api_key = os.environ.get('COVID_API_KEY') #initialize url, query string, and headers url = "https://covid-19-data.p.rapidapi.com/totals" qrystr = {'format':"json"} hdrs = { 'x-rapidapi-host': "covid-19-data.p.rapidapi.com", 'x-rapidapi-key': api_key }
2. Binary files
We’ve described creating a binary file in the section above. And we’ve emphasized that the file creation script must never be packaged with the final product because it is exposed in the create file script.
Here is an example of how you read the file and allocate the API key to a variable.
import io with open("api_file.bin", encoding="utf-8") as binary_file: # Read the whole file at once api_key = binary_file.read() str(api_key)
The variable api_key is used the same way in the main script as described in the environment variables section.
Conclusion
This step-by-step guide highlighted a few useful tips on how to consume the COVID-19 data API when developing an application that requires up-to-date, accurate, and relevant COVID-19 data. It is merely a starting point and not a comprehensive “how to program APIs in Python.” However, it offers useful pointers on consuming the endpoints exposed in the COVID-19 data API offered by RapidAPI.
Leave a Reply