The disease.sh API, available at https://disease.sh/, is a free API that provides data on current global outbreaks, including COVID-19. Its documentation is available at https://disease.sh/docs/. The API endpoint that interests us is https://disease.sh/v3/covid-19/countries/{country}. This endpoint provides data on COVID-19 cases by country. The path parameter {country} is a “iso2” or “iso3” country code. For example, to get data on the United States, you would use the endpoint https://disease.sh/v3/covid-19/countries/US. The response is a JSON object with the following properties: (Note: The values are based on the data at the time of writing.)
Let’s create a src/data/types.ts file to define the types for the API response:
Notice the CovidData interface. This interface defines the shape of the data that we will display in the dashboard. The countryFlag property is the URL to the flag image of the country. The confirmed, active, and recovered properties are the total number of confirmed, active, and recovered cases, respectively.
Let’s define a function that fetches the COVID-19 data for a given country and returns the data in the shape of the CovidData interface. Create a src/data/api.ts file and add the following code:
The fetchCovidData function fetches the COVID-19 data for a given country code and returns the data in the shape of the CovidData interface.
Step 2: Explore the restcountries.com API
The restcountries.com, available at https://restcountries.com/, provides information about countries, including their ISO2 or ISO3 codes. The API endpoint that interests us is https://restcountries.com/v3.1/all. This endpoint provides the list of all countries and their details. The response is a JSON array of objects, with each object representing a country. Each country object has many properties but the ones that interest us have the following structure:
Add the above type definition to the src/data/types.ts file. The cca2 and cca3 properties are the ISO2 and ISO3 codes, respectively. We can use these codes to query the disease.sh API for COVID-19 data.
To define the shape of the data for consuming the list of countries, update the src/data/types.ts file with the following code:
Finally, define a function that fetches the list of countries and their ISO2 and ISO3 codes. Update the src/data/api.ts file with the following code:
Step 3: Putting it all together
For your reference, here is the final structure of the src/data/types.ts and src/data/api.ts files:
The types
The final src/data/types.ts that includes all the types is as follows:
The API functions
The final src/data/api.ts file that includes the API functions is as follows:
Conclusion
In this task, we explored the disease.sh and restcountries.com APIs. We defined the types for the data returned by these APIs and created functions to fetch the COVID-19 data for a given country and the list of countries.
In the next task, we will create the layout and style for the dashboard.