Accessing Data From API Using Python

Introduction 

 
In most Data Science projects, APIs are used to access data.
 
Common reasons for using APIs instead of directly getting data from the server are…
  • Data changes continuously even in seconds.
  • Getting data from the server could be time-consuming.
  • Easy to automate
  • API acts as a direct interface instead of going through any other channel
In this blog, we will learn how to use Python to access data from public APIs
 
This can be done in 3 steps…..
  • Install the Python library ‘Request’
  • Make a ‘GET’ Request using the above library and API Url
  • Store that data in Json format
  • (Optional) Do processing on that data in whatever form you required
Here is the demo code:
  1.  Pip install requests  
  2. Import requests  
  3. response = requests.get("<URL Of the API>")  
Here you can use query parameters as being mentioned in API documentation.
  1. response = requests.get("<URL Of API>", params=parameters)  
Once a request is made, check if the request was successful based on the status codes being mentioned in API documentation.
 
If status code indicates request was successful, store that data in json using the load function of Json, such as:
  1. If (response.status_code == 200)  
  2. json.loads(response.content.decode('utf-8'))  
This would store data in an array, then you could further processing to display data in any format.