Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
api
calls
communitycreator

How to make API calls in Python

Kedar Kodgire

Scope: This post will help you learn to make API calls to fetch dataGET requests using Python.

Data is of the utmost importance these days because it drives applicationsa website, Data Science, Machine Learning Model, etc. and businesses. It is therefore important to learn how to get this data to serve your application.

What is an API?

In basic terms, an API is like a channel that allows applications to communicatesend requests, receive data, and vice versa with one another.

widget

Make your API call

There are different ways to fetch data in Pythonfor example, socket. For this post, we will use the 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.

Code

import requests
import json


class MakeApiCall:

    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")

    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")

    def formatted_print(self, obj):
        text = json.dumps(obj, sort_keys=True, indent=4)
        print(text)

    def __init__(self, api):
        # self.get_data(api)

        parameters = {
            "username": "kedark"
        }
        self.get_user_data(api, parameters)


if __name__ == "__main__":
    api_call = MakeApiCall("https://dev.to/api/articles")

Happy coding!

RELATED TAGS

python
api
calls
communitycreator

CONTRIBUTOR

Kedar Kodgire
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring