API Integration in Python Part 2 - Python Advance Tutorial

Last updated Jan 30, 2021


To fetch any data from a server you have to make a request from a data which is known as an API request. It basically works as- you make a request to an API server and it responded to your request.

To get any data using API you must have to make an API request. There are many types of requests in this library. We are going to work with some major ones. Let's see how to make API requests in python.

If you don't know read What is API and How to work with APIs.

 

How to make API request in python

To make API requests in python we need to have some tools. In python, there is one common library that is used to make a request and work with API. Requests library helps us in working with API.

 

It is not a standard library of python, we have to install this library manually. Here is a tutorial to do that.

To install the Requests library use this command in your terminal.

 

pip install requests

 

If you are using conda then go for this command

conda install requests

 

Once you have installed this library. Let's import it into our program to use it. Follow this import command in your program.

 

import requests

 

Now we are all set to work with this library. Let's get started.

 

Making your First API Request

There are different types of requests we can make. The GET request is mostly used to retrieve data. We are going to use the GET request in our program as we are going to make API requests.

When we will send an API request the API will ping back with a response code that tells us whether our request was successful or not. If there will be something wrong then it will be mentioned in a response code.

Now to send a GET request, we will use the requests.get() function which contains only one argument (In an argument we will add the URL from which we want to make a request). Let's start a coding part.

response = requests.get("http://api.open-demo.org/this-is-a-demo")

 

Here we have used the get() function that returns a response. Now we will use the response.status_code attribute to receive the response code on our screen. Follow this code.

 

print(response.status_code)

 

This line will print the response code on our screen

 

404

 

Here '404' status code means that there is no such file we have requested for. We get this 404 code usually in the websites or any other application page which don't exist. In this program, we requested for this-is-a-demo which definitely does not exist.
There are many status codes in API we can get while requesting. Let's know in brief about some status codes in GET requests.
  • 200- The request is successful and has been returned.
  • 301- This status code means that you have been redirected to any other endpoint. It usually happens when a company or organization changes its domain name or address.
  • 400- It means that the server is defining your request as a bad request. It happens when you send the request for the wrong data.
  • 401- The server believes that you are not authenticated. In most of the API, we require login credentials to get access. This code may occur if you enter the wrong credentials or you are not authenticated.
  • 403- It defines that the resource you are trying to access is forbidden or you don't have permission to access it.
  • 404- We have already used this code in our above example. It defines that the resources you're trying to find are not available on the server.
  • 503- This response code defines that the server is not ready to handle any type of request.

 

Have a look at these status codes, you will notice that codes starting with '4' are some types of errors, and starting with '2' is a successful request. These are some of the major response codes which usually occur. To know more about the status codes go through this documentation.

 

API Documentation

In order to make a successful API request, you must read the API documentation that will help you working with API. Documentation looks so difficult but once you started going through it, you will know how to handle API easily.

 

Now in the above example, we were working with "Open Notify API". It is an open-source API that provides the data of NASA and space. For example, it will tell you about the current location of the international space system and many more. We will make a request from this server in this tutorial.

 

There can be different APIs in one server. Each of these APIs is known as endpoints. It is usually a point, where we want to send our request. For example,

 

http://api.open-notify.org/iss-now.json, which returns data about the current location of the international space station. This API doesn't take any type of inputs. Let's know about this API implementation in brief by making a request in python.

 

We will use the GET request to our endpoint using the request library.

 

response = requests.get("http://api.open-notify.org/iss-now.json")
print(response.status_code)

 

By making this request we will get the response code which tells us about the status of our request.

200

Here the status code we received is '200' which means that our request was successfully made. Now we will use the response.json() method to get the data we received from the server.

 

print(response.json())

[{'message': The ISS is currently over -33.127° N, -76.746° E, 'craft': 'ISS'}]

 

Working with JSON Data in Python

JSON full form is javascript object notation. It is a language of APIs to fetch the data we get from the servers. In simple words, it is just a way to encode the data we received from the servers in a primary format. It seems difficult to work with JSON but you can easily master the JSON language with this quick tutorial.

 

Python Example on  Read JSON file in Python

 

 

You will notice that the above data we received from the server is in some type of format which is quite similar to Python dictionaries and lists. This is JSON language. Here is a small example to explain you JSON.

 

[

 

    {

 

        "message""The ISS is currently over -33.127° N, -76.746° E",
 
        "craft""ISS"
 
    }
 
    {
 
        "message""The ISS is currently over -43.227° N, -26.546° E",
 
        "craft""ISS"
 
    }
 
]

 

The JSON library has 2 main functions:

  • json.dumps()- This function takes the python object as an input and converts it into a string. The dump function is generally used to print a formatted string which makes the JSON output understandable.
  • json.loads()- It takes a JSON string and converts it into a Python object

 

 

Full Program to Make First API Request in Python

resp = requests.get('https://todolist.example.com/tasks/'
 
if resp.status_code != 200# This means something went wrong. 
    raise ApiError('GET /tasks/ {}'.format(resp.status_code)) 
 
for todo_item in resp.json(): 
    print('{} {}'.format(todo_item['id'], todo_item['summary']))
 

 

In this code first of all we have made a request from the server. If the API request is successful we can print the data we received back from the server. Else it will print the response code which will tell us about the error we are facing.

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

325 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions