23: Consuming APIs in Python
Consuming APIs in Python
We are living in the world of information. Machines are connected to each other and they share the data. The Internet provides a huge infrastructure to store and provide data on demand. In many cases, it is required to connect to some server and send a request to ask for information. APIs are the latest way that provides data over the network in a secure and efficient way.
- The complete name is RESTful APIs (REpresentational State Transfer Application Programming Interfaces).
- ful means fully supported.
- These are also called Web APIs.
- We will use word API in the lecture.
- Data transfer from one computer to another is a very old technique which was developed in the 1960s.
- The real boost was provided when protocols were introduced.
- Many evolutionary steps were taken over the time period like CORBA, RMI, SOAP Services, RPC and the latest form is RESTful.
Figure 1: RESTful API Overview
- We have already discussed the concept of library functions.
- Calling a RESTful API is similar to calling a library function but this time the library function is hosted on some remote server. When this remote function is called, the RAM and CPU of the server will be consumed.
- You can call this library function from your PC, mobile app or event gaming console.
- When a server receives a RESTful API call, its response may approve the request and send response or may be declined.
- Following terminologies are important
- Client: The application that sends the request.
- Server: The application that responds to the request (approve or decline).
- Resource: address of the server this is similar to website URL.
- Endpoint: Name of the function that I want to execute.
- HTTP Method: Which operation should be performed on successful request.
- GET: Get some data from server
- POST: Saving some data on server
- PUT: Change some already existing data.
- DELETE: Remove some data on the server.
- There are other methods also available.
- API Key / Token: Encrypted string that works like a password for server. If the server implements the authentication, then this password would be required on each call.
- Payload: Data that is sent to the server. It is also called message body
- Status Code: This is 3-digit code that is sent from the server with a response. Before examining the response, we can identify what happened with our request on the server. Some popular status codes are as follows.
- 200: Server found the request, accepted and executed successfully.
- 301: Server address moved or changed.
- 400: Invalid request from client.
- 401: Client unauthorized the request. Normally, asking for password (API Key)
- 403: Client cannot send request for particular operation.
- 404: Invalid server address or server not found.
- 500: Server received the request and accepted but when executed, some error occurred.
- 502: Bad gateway. The server called some other server and the second server did not respond.
- Response Body: This is an actual response from the server. Normally, it is in JSON format but sometimes in simple text or XML.
- To understand the concept of Web API, we consider an example of a JSON lecture where two different applications were running. One was the Admission System and the other was the Examination system.
- The Admission System is completely different and independent from the Examination System.
- To share the data with the Examination System, it is required to develop an API on the Admission System that provides students data.
- This API (resource, end point, HTTP method and token) must be provided to developers who are working on the Examination System.
- Now the Admission System is server and Examination System is client.
- Examination System sends request and Admission System response with student data (if no issue with communication)
- In this lecture we will only learn how we can send the request.
- API development required some server-side technologies (Django or Laravel or any other) hands-on expertise.
- We will not discuss server side in this lecture.
- Some APIs are publicly available like API from weather.com but most APIs are closed on available for internal use.
- Some APIs are also available for educational purposes.
- We will use https://free-apis.github.io. Here we can find many educational APIs.
- We will use Dog API (https://dogapi.dog).
- There are many end points available for it. Our end point will be breeds
- The URL for API will be https://dogapi.dog/api/v2/breeds
- We will call it’s “get” method.
- This end point will return breed data along with some other information.
- Parameter based results are also available but due to simplicity we will just focus on calling a simple get API.
- You can find more information from https://dogapi.dog/docs/api-v2
- There are some tools also available to verify the working of APIs like Postman, Swagger, and Thunder Client.
- This API is also configured with Swagger.
- So, you can also run it online and test.
- The API developers normally test the APIs online but for client-side developers should also test it with client tools.
- We will use Thunder Client.
Thunder Client
- Thunder Client used to test the working of APIs (public or private).
- We can test APIs with writing code.
- It is always a good practice to test the API before calling it in your code.
- We can install Thunder Client simply in Visual Studio Code as an extension.
- Click on the extension icon in the activity bar.
- Type Thunder Client and click on the blue small “install” button under it.
Figure 2: Installing Thunder Client in VS Code
- I have already installed this tool so the blue “install” button is not looking here.
- After installation, we can find Thunder Client icon in activity bar
- By clicking on this icon, the Thunder Client window will be open.
Figure 3: Launching Thunder Client by clicking Icon in Activity Bar
- The Activity tab looks empty because no API has been tested yet.
- To test the provided Dog API, just click on the New Request button.
- It will generate a simple Web API request in the main window.
Figure 4: Sending API Request by providing URL in Thunder Client
- You can see a GET method. From this drop down you can select any other method.
- We will type a full URL including the end point in the address bar.
- Click the Send button to send the request to the server.
- Whichever server response, the result will be shown in the Response area.
Figure 5: Response in Thunder Client
- We send the request on https://dogapi.dog/api/v2/breeds
- After a short while it returned the response below.
- We can see that Status is 200 means OK. The server accepts the request and response.
- The total size of response is 5.64KB.
- It took 1.61 seconds to get a response. This time varies due to your internet speed, load on server and size of response.
- We can see the JSON data underneath and scroll it can see the complete data. The data is large enough. We can save it in a JSON file if required. In our example, we don’t need to save the response in file.
- If status is more than 400 then it will be a faulty response. Most probably we will not receive JSON.
- The above example runs excellently and we get a proper response so our test is successful.
Python Code to Call API
- Now we will do it in Python code.
- To generate a Web API request and response, we have to use the requests library.
- This library is not by default in our Python libraries.
- We have to get this library, run this command in the terminal.
pip install requests
Code 1: Installing requests Library for Consuming APIs
- This command will automatically download and install the requests library.
- After successful installation of requests, write the following code in the new code file.
import requests res = requests.get("https://dogapi.dog/api/v2/breeds")dog_data = res.json()print(dog_data)
Code 2: Calling API with Python Code
- The code, first, imports the library
- The library has a get function that accepts a string parameter which is the complete URL of the end point.
- The get function will take some time to execute and return the response in res variable.
- The res variable has a response in binary format which is not directly readable, we use the json function to convert binary data into a dictionary name dog_data.
- When we print the dog_data, it will print a huge JSON returned from the server.
- When we have JSON data, we can perform operations on it.








