Jun 7, 2020

How To: Call a REST API using Python(GET Service)

This blogpost gives you the code to hit the REST api and validate the response with basic checks. We will be using the requests library to request a call to Rest API. For example purpose, I will be using the weather API from openweathermap.org which is partially free and is sufficient for our purpose.

Pre-requisites:


  1. Python 3 version on the machine
  2. Requests library installed (Click here to know the installation process)
  3. openweathermap.org API keys: Even though some of the Rest API are free, it is not exposed directly. Click here to know the process of getting the API keys.
Below is the API that we will be requesting the REST call, it is current weather data by City name

api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key}

Before writing the code, let us test the api on web browser.

With a valid city name:


With invalid city name:
                                          

Below is the full-fledged Python Code:


 ##this step imports the requests library
import requests

##define and assign varibles for Rest URL, API Key and City name
Rest_URL = "http://api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key}"
API_Key = '320e5a070b733dc8272eada708c76e1e'
city_name='Hyderabad'

##Replace the cityname and api key in Rest_URL to make it useful
modified_url = Rest_URL.replace("{city name}",city_name).replace("{your api key}",API_Key)
print(modified_url)


##Now the API URL base is ready, now let us call it and save the response in a variable
response = requests.get(modified_url)


## now the is executed but we have to make sure that it is returning the expected value
## For this purpose, we gonna check the response code and response content

##A successful request will always send 200 as response code, well most of the times 
if response.status_code == 200:
    print("True : connection established successfully")

    ##now the response status is as expected let us validate the content of it
    ## Note: The response content is in JSON format so we need to parse the JSON
    ## no worries, requests library can handle the JSON directly
    json_response = response.json()

    ## first check if the response contains the name key or not
    if 'name' in json_response.keys():
        ##now check the name value is Hyderabad or not
        if json_response['name'] == 'Hyderabad':
            print("True : The content returned is accurate")
        else:
            print("False : The content returned is inaccurate")
    else:
        print("False : "+city_name+json_response['message'])
else:
    print("False : connection establishment failed with code "+str(response.status_code))
 

Now let us understand the important code chunks,

First of all, like every programming language, we have to import the libraries so that we can use them in our code. here I am importing the 'requests' library as I will be using it for performing the call to REST API.

>>> import requests 

now, let us create variables and assign them with values of main REST URL, API key and city name


>>> Rest_URL = "http://api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key}"
>>> API_Key = '320e5a070b733dc8272eada708c76e1e'
>>> city_name='Hyderabad'

as you can see that I have not fully formed the Rest_URL variable with the data. So my next would be to modify the URL with the data values.
For this, I will be using the replacement function and we can see that values are placed in the respective positions.

>>> modified_url = Rest_URL.replace("{city name}",city_name).replace("{your api key}",API_Key)
>>> print(modified_url)
http://api.openweathermap.org/data/2.5/weather?q=Hyderabad&appid=320e5a070b733dc8272eada708c76e1e
our url is ready now we will be using the get method of requests to call this API.


>>> response = requests.get(modified_url)
let us check if the response status is 200 or not

>>> response.status_code
200
Hurray, the status code is 200, let us print the entire response

>>> response.json()
{'coord': {'lon': 78.47, 'lat': 17.38}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': 'scattered clouds', 'icon': '03d'}], 'base': 'stations', 'main': {'temp': 306, 'feels_like': 308.71, 'temp_min': 305.15, 'temp_max': 307.15, 'pressure': 1009, 'humidity': 52}, 'visibility': 6000, 'wind': {'speed': 2.6, 'deg': 300}, 'clouds': {'all': 40}, 'dt': 1591515717, 'sys': {'type': 1, 'id': 9214, 'country': 'IN', 'sunrise': 1591488668, 'sunset': 1591535950}, 'timezone': 19800, 'id': 1269843, 'name': 'Hyderabad', 'cod': 200}

As you can see , like mentioned in full fledged code, we can use the json() method to extract the json content and evaluate it for accuracy