Scope: This post will help you learn to make API calls to
using Python. fetch data GET requests
Data is of the utmost importance these days because it drives
In basic terms, an API is like a channel that allows applications to
There are different ways to socket
requests
module in Python. The requests
module is a simple, yet elegant, HTTP library. To install this library, use the following command:
pip install requests
To check the installed version, use the following command:
pip freeze | grep requests
requests==2.22.0
Looks like your environment is now ready to throw some requests
.
def get_data(self, api):
response = requests.get(f"{api}")
if response.status_code == 200:
print("sucessfully fetched the data")
self.formatted_print(response.json())
else:
print(f"Hello person, there's a {response.status_code} error with your request")
As seen above, we first check the status code and then print the data. This code tells us about the response that has been received based on our requests. The 200
code tells us that we have received the info successfully. Multiple codes indicate different responses, as shown below:
Code | Status | Description |
200 | OK | The request was completed. |
201 | Created | A new resource was successfully created. |
400 | Bad Request | The request was invalid. |
401 | Unauthorized | The request did not include an authentication token or the authentication token was expired. |
403 | Forbidden | The client did not have permission to access the requested resource. |
404 | Not Found | The requested resource was not found. |
405 | Method Not Allowed | The HTTP method in the request was not supported by the resource. For example, the DELETE method cannot be used with the Agent API. |
409 | Conflict | The request could not be completed due to a conflict. For example, POST ContentStore Folder API cannot complete if the given file or folder name already exists in the parent location. |
500 | Internal Server Error | The request was not completed due to an internal error on the server-side. |
503 | Service Unavailable | The server was unavailable. |
Similarly, we can also make the API call with some parameters. In this case, let’s fetch articles of a particular user: me.
parameters = {
"username": "kedark"
}
I have stored the parameters in a variable; now, let’s make an API call with the same paramters.
def get_user_data(self, api, parameters):
response = requests.get(f"{api}", params=parameters)
if response.status_code == 200:
print("sucessfully fetched the data with parameters provided")
self.formatted_print(response.json())
else:
print(
f"Hello person, there's a {response.status_code} error with your request")
To print the data in our program, we will be using the response.json()
method, which returns a JSON object of the result (if the result was written in JSON format; if not, it raises an error).
Similarly, we have different methods that will return different information.
Property/Method | Description |
apparent_encoding | Returns the apparent encoding |
close() | Closes the connection to the server |
content | Returns the content of the response, in bytes |
cookies | Returns a CookieJar object with the cookies sent back from the server |
elapsed | Returns a time delta object with the time elapsed from sending the request to the arrival of the response |
encoding | Returns the encoding used to decode r.text |
headers | Returns a dictionary of response headers |
history | Returns a list of response objects holding the history of request (URL) |
is_permanent_redirect | Returns True if the response is the permanently redirected URL, otherwise False |
is_redirect | Returns True if the response was redirected, otherwise False |
iter_content() | Iterates over the response |
iter_lines() | Iterates over the lines of the response |
json() | Returns a JSON object of the result (if the result was written in JSON format; if not, it raises an error) |
links | Returns the header links |
next | Returns a PreparedRequest object for the next request in a redirection |
ok | Returns True if status_code is less than 400, otherwise False |
raise_for_status() | If an error occurs, this method returns a HTTPError object |
reason | Returns a text corresponding to the status code |
request | Returns the request object that requested this response |
status_code | Returns a number that indicates the status (200 is OK, 404 is Not Found) |
text | Returns the content of the response, in unicode |
url | Returns the URL of the response |
It is a good exercise to try them one by one. This data can now be used to feed your application.
Let’s enhance our understanding by sending a few HTTP requests on an API server.
In the following coding example, we are fetching the list of products from an API server.
Note: We are using Fake Store API it is open source API that can be used for Pseudo-real data for testing our API calls.
import requestsimport jsonclass MakeApiCall:def get_data(self, api):response = requests.get(api)if response.status_code == 200:print("Successfully fetched the data")self.formatted_print(response.json())else:print(f"Error: {response.status_code}. Failed to fetch data.")print("Response content:", response.content)def formatted_print(self, obj):text = json.dumps(obj, sort_keys=True, indent=4)print(text)def __init__(self, api):self.get_data(api)if __name__ == "__main__":api_call = MakeApiCall("https://fakestoreapi.com/products")
Lines 1&2: We imported all the required libraries that we will use to make the API call.
Lines 7-14: We defined the get_data()
function with the API endpoint as its parameter in the function we are making a GET
API request to the server to get a list of products from the API server.
Lines 16-18: We defined a formatted_print()
function that will format the API server response for us.
In the following coding example, we are adding a product with an API call.
import requestsimport jsondef make_api_call():url = "https://fakestoreapi.com/products"data = {"title": "Testing product","price": 16.5,"description": "lorem ipsum set",}headers = {"Content-Type": "application/json"}response = requests.post(url, json=data, headers=headers)print(response.json())if __name__ == "__main__":make_api_call()
Lines 1&2: We imported all the required libraries that we will use to make the API call.
Lines 4-14: We defined the make_api_call()
function in which we are making a POST
API request to the server to post a new product to the API server with all the parameters required for the call.
Happy coding!
Free Resources