The world was barely recovering from the Coronavirus pandemic when the new variants started wreaking havoc – amid the mass vaccination campaigns around the world. At the time of writing, 44.5% of the world population has received at least one dose of covid-19 vaccine. However, breakthrough infections are still being reported among fully vaccinated people and are a cause for concern. WHO declared delta variant as the highly contagious virus strain, and that the Coronavirus will mutate like the flu, which is likely here to stay.
As per many virologists and researchers, the virus will change with time and it will try to find ways to evade the immunity (obtained either by vaccination or infection). The new waves of the COVID-19 pandemic are still raging worldwide, causing major health and economic disruptions and several states are under lockdown again. It’s becoming evident that now is not the time to let the guard down and hence accurate tracking of emerging data is still crucial to governments and policymakers. Numerous applications and services have been built and launched, since the pandemic began, to provide accurate statistics for coronavirus.
One such service is COVID-19 API, which makes it super easy for application developers, researchers, and AI enthusiasts to build and launch their coronavirus tracking applications or websites.
It is recommended to go through this post at first – if you are new to the APIs.
What is COVID-19 API?
COVID-19 API is a Restful API that allows users to fetch real-time and historical statistics for coronavirus, such as the total and active cases , number of tests performed, and deaths around the world and also at the country level.
The API is free to use and provides three simple endpoints that can be used to build a variety of applications such as Covid-19 tracker websites and apps, machine learning models to build predictive and forecasting algorithms. The statistics are updated every 15 minutes, allowing their users to provide a near real-time picture of the coronavirus for their region.
Furthermore, the API is structured in a way that it can be consumed easily by novice users. Unlike other services that provide multiple endpoints for complex operations, the COVID-19 API keeps it simple by providing three simple endpoints that can be used to provide the following functionalities:
- Retrieves the list of countries affected by the coronavirus.
- Fetch current status of the spread of the coronavirus in those countries.
- Get historical statistics for any country.
The API has a latency of 550ms, which makes it ideal to integrate with high performant applications and websites. One can make unlimited requests in a month while keeping the usage under 60 requests per minute, which is the only limit it imposes.
How does the COVID-19 API work?
The COVID-19 API in an Application Programmable Interface that strictly follows the REST principles and contains endpoints that can be executed over the web to get covid-19 statistics using various programming languages and frameworks.
It works in the following way:
The Client requests the resources by calling one of its endpoints using the GET method over HTTPS. The Server processes the request, prepares the data and sends it back to the client as JSON formatted response. In addition to the requested data, the response also contains meta-data such as GET action, parameters list, errors, result, and response count.
The following diagram illustrates the high-level overview of the COVID-19 API.
Who can use the COVID-19 API?
COVID-19 API is built for application developers who are aiming to build coronavirus tracker applications and dashboards using the web or mobile technologies. In addition to that, the API is also useful for news websites and media outlets to provide accurate and up-to-date statistics about the coronavirus spread.
The API also allows the users to fetch historical data which is super helpful for data scientists and AI enthusiasts to build various machine learning models and predictive algorithms.
Third-party plugin developers can also use this API to build various plugins and widgets for their CMS. One such example is the WordPress plugin directory – where plugin developers are offering various plugins and widgets related to covid-19 statistics and updates.
How to Connect to COVID-19 API Tutorial – Step by Step
COVID-19 API can be seamlessly connected to your apps using the RAPIDAPI platform.
This process can be summarized in three steps:
Step1: Signup for an Account on RapidAPI
First, you need to create an account on RapidAPI (where you can find and connect to thousands of APIs using a single SDK, API key, and Dashboard). You can also use your social logins such as Google, Github, or Facebook as the RapidAPI also supports Single-Sign-On (SSO).
Step2: Search the API Marketplace
After successful registration, you will be redirected to the dashboard. Navigate to “API Marketplace” and search for “COVID-19 API“.
Select the API from the result set by clicking on the “COVID-19” item. It will take you to the API’s home page.
Step 3: Test the API
The API is completely free, so you can begin testing its endpoints right away. Navigate to the ‘Endpoints’ tab and select the ‘countries’ endpoint.
You would notice that the required header parameters like API Key and Host information are automatically generated by RapidAPI Console. You can click on the ‘Test Endpoint’ button to execute the request.
You should be able to see the API response in the Results tab (as shown in the below image).
Note: The server response also contains a JSON variable ‘errors’ that may contain detailed information in case of any additional errors. Alternatively, it may return one of the following responses instead of 200.
- 400 Bad Request – Client sent an invalid request (missing required parameters).
- 401 Unauthorized – Failed to authenticate with the API server.
- 403 Forbidden – The client authenticated but didn’t have permission to access the required resource.
- 404 Not Found – The requested resource (endpoint) doesn’t exist.
- 500 Internal Server Error – A generic error occurred on the API server.
- 503 Service Unavailable – The API service is not available.
Explanation of the COVID-19 API Endpoints
The COVID-19 API has three endpoints which are explained below.
1. Countries
This endpoint returns the list of all countries affected by the Coronavirus. It has an optional parameter ‘search’ of type ‘string’. Users may fill this field to search for a specific country.
Below is the sample request which executes this endpoint by providing a search parameter: ‘spa’
It can be observed from the image that the API returns all the countries matching the search criteria. The Search parameter enforces the minimum limit of three characters, otherwise, it will throw an error as below:
In this case, the results array is empty but the errors array contains the object with the detailed error message. You may notice that the response code is still 200 (OK) but the JSON object has the meta-data fields which can be used to detect if there’s an error in the request processing due to malformed input or other server issues. If the ‘search’ parameter is left empty, the API will return the list of all countries as shown in the below image.
2. Statistics
This endpoint fetches the global and country-level statistics of the spread of the Coronavirus. It has an optional parameter called ‘search’ which can be used to filter the data for any country.
Below is the API response when the endpoint is invoked for ‘usa’:
The same endpoint can be used to fetch global statistics for coronavirus, the only difference, in this case, is that the search parameter expects the value ‘all’.
Explanation of the API Response
The API response has two parts:
- Meta-data fields
- Response object
Meta-Data Fields:
COVID-19 API makes it easier for developers to identify the response with the help of meta-data fields which are part of every successful (200 OK) response.
get | This field contains the name of method that was invoked by a client app. |
parameters[] | This is an array which contains key value pair of the parameter of the endpoint and the value provided by the client. |
errors[] | If there were any errors encountered by the API during request processing – they will be included inside this array. |
results | This field represents the total results returned by the API |
response[] | This array contains the requested data returned by the API as JSON object. |
The Response Object:
continent | |
country | Name of the country |
population | Total population of a given country |
cases[] | This array contains detailed statistics for coronavirus spread for the given country
1M_pop -> this field contains the total number of cases per one million |
deaths[] | This array contains the statistics for deceased cases and have following fields:
|
tests[] | This array simply contains two fields indicating total test conducted and number of tests per one million population. |
day/ time | These fields are used to contain the current date and time and incase of history endpoint- this will indicate the provided date |
3.History
This endpoint can be used to deliver the historical statistics for any date in the past. It’s very similar to the statistics endpoint and uses the same structure, but takes an additional parameter ‘day’ in (YYYY-MM-DD) format.
In the following example, we can see the API response when the endpoint was invoked to find out the statistics of the USA on 2020-06-02.
How to use COVID-19 API with Python
The following code snippet uses http.client to fetch the latest statistics for the country USA using the COVID-19 API.
Note: Please make sure that you have installed Python before running this code example.
import http.client conn = http.client.HTTPSConnection("covid-193.p.rapidapi.com") headers = { 'x-rapidapi-host': "covid-193.p.rapidapi.com", 'x-rapidapi-key': "ce19d0164fmsh3d383efc0e85ce5p16dcb1jsnb1a4a3c79541" } conn.request("GET", "/statistics?country=usa", headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))
How to use COVID-19 API with PHP
Before running the sample code shared below, please make sure that you have installed PHP. You may follow this guide on how to install this correctly.
The below code example using PHP’s curl library to invoke the history endpoints with query parameters.
<?php $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://covid-193.p.rapidapi.com/history?country=usa&day=2020-06-02", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => [ "x-rapidapi-host: covid-193.p.rapidapi.com", "x-rapidapi-key: ce19d0164fmsh3d383efc0e85ce5p16dcb1jsnb1a4a3c79541" ], ]); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; }
How to use COVID-19 API with Ruby
The below code uses Ruby to execute the ‘countries’ endpoint to fetch all the affected countries.
require 'uri' require 'net/http' require 'openssl' url = URI("https://covid-193.p.rapidapi.com/countries") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) request["x-rapidapi-host"] = 'covid-193.p.rapidapi.com' request["x-rapidapi-key"] = 'ce19d0164fmsh3d383efc0e85ce5p16dcb1jsnb1a4a3c79541' response = http.request(request) puts response.read_body
How to use COVID-19 API with Javascript
To use the API in JavaScript, you need to first set up the JavaScript environment. You can download text editors such as Atoms, Visual Studio Code, NotePad++ for this purpose.
The following code snippet invokes the history endpoint to fetch the Coronavirus statistics for the United Kingdom on 2020-06-02.
fetch("https://covid-193.p.rapidapi.com/history?country=UK&day=2020-06-02", { "method": "GET", "headers": { "x-rapidapi-host": "covid-193.p.rapidapi.com", "x-rapidapi-key": "ce19d0164fmsh3d383efc0e85ce5p16dcb1jsnb1a4a3c79541" } }) .then(response => { console.log(response); }) .catch(err => { console.error(err); });
We can see from the below image that the code was executed successfully.
Benefits
Speed
COVID-19 API takes half a second to pull the latest statistics for any given country which gives developers enough time to deliver the results to their clients using any UI or charts.
Reliability
Another important factor is the reliability of the data. No one would be interested in getting insufficient or unreliable data- regardless of how fast it is. COVID-19 API takes this into consideration by taking data from trusted sources only which is updated every 15 minutes.
Historical Data
COVID-19 API gives its user access to historical statistics as well, which opens up opportunities for data scientists, epidemiologists to use this data for a variety of purposes – from building predictive models to displaying historical timelines using charts and graphs.
Cost
The API is free of cost and can be ideal for small startups and developers who are just testing the waters with their prototypes and MVP.
Alternatives to COVID-19API
There are some alternatives to COVID-19 API, which are described below.
- COVID-19 Data: This is a freemium API which provides several endpoints to get coronavirus statistics and uses multiple sources. It also offers paid plans to remove the monthly quota and requests per minute limits.
- COVID-19 Statistics API: This API is based on public data by Johns Hopkins CSSE and provides an overview of the global cases.
- COVID-19 Tracking API: This is the Free API that uses the scraping technique to fetch the live statistics from the Worldometers.com website.
- Coronavirus Map API: This API provides free covid-19 live updates and also provides historical data, maps, charts, and graphs.
- EU COVID-19 Travel API: This is a free API which provides data such as Covid-19 incidence rates and travel restrictions/requirement from the European Open Data Portal.
Summary
In this article, we have learned about COVID-19 API and how it can be integrated with various applications and plugins, ranging from coronavirus tracking dashboards to news websites, CMS plugins and Machine learning algorithms. It also highlights all the endpoints in detail and demonstrates how these endpoints can be consumed in a variety of programming languages such as Python, PHP, Ruby, and JavaScript.
Leave a Reply