Get Covid-19 Statistics from Internet using REST API with Python!
Umair Khan Patel
Security Delivery Team Lead at Accenture | Risk and Compliance Management | CISA | ISO 27001 LA | CEH Practical
If you have read my last article I have shown you how to retrieve data from internet using ‘web scrapping’. In this article I am going to show you how to retrieve data from the internet using REST API.
What is API?
API stands for Application Programming Interface. It works just like any other communication protocol where client sends a query for specific data and the server responds with the appropriate data. On server side, a developer can configure the server, in a way, that a specific data will be sent to the client if it sends a request to a specific URL.
So, each URL is a request and the data you get is a response.
Python has libraries that we can use to avoid writing lengthy programs and instead use functions from those libraries. We are going to use the below listed libraries in this program.
import requests import json
Requests is used to handle the HTTP requests without any complexities.
Json is used to read and manipulate the json data that we are going to receive as a response.
We are going to use the open source API available on the below website
https://api.rootnet.in/covid19-in/stats/latest
in order to make a request use the following code
url = requests.get('https://api.rootnet.in/covid19-in/stats/latest')
This will save the response received in the variable ‘url’.
At any point of time you can use the ‘print’ statement to display the data in the variables.
Now, we are going to use two functions ‘json.loads’ and ‘json.dumps’ to manipulate the data and then finally print it.
What ‘json.loads’ does is that it takes a string as input and returns a json object as an output.
jsondata = json.loads(url.content.decode('utf-8'))
the above code will convert the data in the variable ‘url’ into json object.
If we print the variable ‘jsondata’ we will get all the output in a single line.
THIS DOES NOT LOOK BEAUTIFUL!!! (or readable)
So, let’s beautify it!
Now we will use ‘json.dumps’ in order to convert the json object into a python object, so we can manipulate it easily and then finally print it. And below code will do that.
data2 = json.dumps(jsondata, indent=2)
The ‘indent’ parameter is used to format the indent level of the string.
Cool! We’re done! Now let’s print it!
print(data2)
Output: (Does it not look charming?)
Thank you for reading! Hit Like you found the article helpful!
Teacher at Engineering
4 年Sir, How to use this command " data2 = json.dumps(data, indent=2)" . Because when I am using it in Jupyter note book, I am getting the following error "TypeError: Object of type Response is not JSON serializable". How to get same output as like given by you "Output: (Does it not look charming?)".