Uncategorized

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.

  1. The complete name is RESTful APIs (REpresentational State Transfer Application Programming Interfaces).
  2. ful means fully supported.
  3. These are also called Web APIs.
  4. We will use word API in the lecture.
  5. Data transfer from one computer to another is a very old technique which was developed in the 1960s.
  6. The real boost was provided when protocols were introduced.
  7. 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

  1. We have already discussed the concept of library functions.
  2. 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.
  3. You can call this library function from your PC, mobile app or event gaming console.
  4. When a server receives a RESTful API call, its response may approve the request and send response or may be declined.
  5. Following terminologies are important
  6. Client: The application that sends the request.
  7. Server: The application that responds to the request (approve or decline).
  8. Resource: address of the server this is similar to website URL.
  9. Endpoint: Name of the function that I want to execute.
  10. HTTP Method: Which operation should be performed on successful request.
  11. GET: Get some data from server
  12. POST: Saving some data on server
  13. PUT: Change some already existing data.
  14. DELETE: Remove some data on the server.
  15. There are other methods also available.
  16. 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.
  17. Payload: Data that is sent to the server. It is also called message body
  18. 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.
  19. 200: Server found the request, accepted and executed successfully.
  20. 301: Server address moved or changed.
  21. 400: Invalid request from client.
  22. 401: Client unauthorized the request. Normally, asking for password (API Key)
  23. 403: Client cannot send request for particular operation.
  24. 404: Invalid server address or server not found.
  25. 500: Server received the request and accepted but when executed, some error occurred.
  26. 502: Bad gateway. The server called some other server and the second server did not respond.
  27. Response Body: This is an actual response from the server. Normally, it is in JSON format but sometimes in simple text or XML.
  28. 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.
  29. The Admission System is completely different and independent from the Examination System.
  30. To share the data with the Examination System, it is required to develop an API on the Admission System that provides students data.
  31. This API (resource, end point, HTTP method and token) must be provided to developers who are working on the Examination System.
  32. Now the Admission System is server and Examination System is client.
  33. Examination System sends request and Admission System response with student data (if no issue with communication)
  34. In this lecture we will only learn how we can send the request.
  35. API development required some server-side technologies (Django or Laravel or any other) hands-on expertise.
  36. We will not discuss server side in this lecture.
  37. Some APIs are publicly available like API from weather.com but most APIs are closed on available for internal use.
  38. Some APIs are also available for educational purposes.
  39. We will use https://free-apis.github.io. Here we can find many educational APIs.
  40. We will use Dog API (https://dogapi.dog).
  41. There are many end points available for it. Our end point will be breeds
  42. The URL for API will be https://dogapi.dog/api/v2/breeds
  43. We will call it’s “get” method.
  44. This end point will return breed data along with some other information.
  45. Parameter based results are also available but due to simplicity we will just focus on calling a simple get API.
  46. You can find more information from https://dogapi.dog/docs/api-v2
  47. There are some tools also available to verify the working of APIs like Postman, Swagger, and Thunder Client.
  48. This API is also configured with Swagger.
  49. So, you can also run it online and test.
  50. The API developers normally test the APIs online but for client-side developers should also test it with client tools.
  51. We will use Thunder Client.

Thunder Client

  1. Thunder Client used to test the working of APIs (public or private).
  2. We can test APIs with writing code.
  3. It is always a good practice to test the API before calling it in your code.
  4. We can install Thunder Client simply in Visual Studio Code as an extension.
  5. Click on the extension icon in the activity bar.
  6. Type Thunder Client and click on the blue small “install” button under it.

Figure 2: Installing Thunder Client in VS Code

  1. I have already installed this tool so the blue “install” button is not looking here.
  2. After installation, we can find Thunder Client icon in activity bar
  3. By clicking on this icon, the Thunder Client window will be open.

Figure 3: Launching Thunder Client by clicking Icon in Activity Bar

  1. The Activity tab looks empty because no API has been tested yet.
  2. To test the provided Dog API, just click on the New Request button.
  3. It will generate a simple Web API request in the main window.

Figure 4: Sending API Request by providing URL in Thunder Client

  1. You can see a GET method. From this drop down you can select any other method.
  2. We will type a full URL including the end point in the address bar.
  3. Click the Send button to send the request to the server.
  4. Whichever server response, the result will be shown in the Response area.

Figure 5: Response in Thunder Client

  1. We send the request on https://dogapi.dog/api/v2/breeds
  2. After a short while it returned the response below.
  3. We can see that Status is 200 means OK. The server accepts the request and response.
  4. The total size of response is 5.64KB.
  5. It took 1.61 seconds to get a response. This time varies due to your internet speed, load on server and size of response.
  6. 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.
  7. If status is more than 400 then it will be a faulty response. Most probably we will not receive JSON.
  8. The above example runs excellently and we get a proper response so our test is successful.

Python Code to Call API

  1. Now we will do it in Python code.
  2. To generate a Web API request and response, we have to use the requests library.
  3. This library is not by default in our Python libraries.
  4. We have to get this library, run this command in the terminal.
pip install requests

Code 1: Installing requests Library for Consuming APIs

  1. This command will automatically download and install the requests library.
  2. 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

  1. The code, first, imports the library
  2. The library has a get function that accepts a string parameter which is the complete URL of the end point.
  3. The get function will take some time to execute and return the response in res variable.
  4. 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.
  5. When we print the dog_data, it will print a huge JSON returned from the server.
  6. When we have JSON data, we can perform operations on it.

Leave a Reply

Your email address will not be published. Required fields are marked *