×

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental terms, an API resembles a channel that permits applications to speak with each other.

Make your API decision

There are various ways of bringing information in Python. For this post, we will involve the solicitations module in Python. The solicitations module is a basic yet rich HTTP library. To introduce this library, utilize the accompanying order:

pip introduce requests

To really look at the introduced form, utilize the accompanying order:

pip freeze | grep requests
 requests==2.22.0

Seems as though your current circumstance is presently prepared to toss a few solicitations.

def get_data(self, api):
        response = requests.get(f"{api}")
        if response.status_code == 200:
            print("successfully 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 afterwards print the information. This code informs us regarding the reaction that has been gotten in view of our solicitations. The 200 code lets us know that we have gotten the data effectively. Numerous codes demonstrate various reactions, as displayed underneath:

CodeStatusDescription
200OkThe solicitation was finished.  
201CreatedAnother asset was effectively made.
400Bad RequestThe request was invalid
401UnauthorizedThe solicitation did exclude a verification token, or the confirmation token was terminated.
403ForbiddenThe client didn't have the authorization to get to the mentioned asset.
404Not foundThe mentioned asset was not found.
405Method not allowedThe HTTP technique in the solicitation was not upheld by the asset. For instance, the DELETE strategy can't be utilized with the Agent API.
409ConflictThe solicitation couldn't be finished because of contention. For instance, POST ContentStore Folder API can't finish assuming the given document or envelope name as of now exists in the parent area.
500Internal server errorThe solicitation was not finished because of an inside blunder on the server side.
503Service UnavailableThe server was unavailable

Essentially, we can likewise settle on the API decision for certain boundaries. For this situation, we should get articles from a specific client: me.

boundaries = {
            "username": "kedark"
        }

I have put away the boundaries in a variable; presently, we should settle on an API decision with similar parameters.

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

API Documentation

To guarantee we make a fruitful solicitation, when we work with APIs counselling, the documentation is significant. Documentation can appear to be startling from the get-go, yet as you use documentation increasingly more, you'll find it gets simpler. We'll be working with the Open Notify API, which gives admittance to information about the worldwide space station. It's an extraordinary API for learning since it has an exceptionally straightforward plan and doesn't need confirmation. We'll show you how to involve an API that requires validation in a later post. Frequently there will be numerous APIs accessible on a specific server. Every one of these APIs are ordinarily called endpoints.

The principal endpoint we'll utilize is http://api.open-notify.org/astros.json, which returns information about space explorers presently in space. Assuming you click the connection above to take a gander at the documentation for this endpoint, you'll see that it says This API takes no data sources. This makes it a straightforward API for us to begin with. We'll begin by making a GET solicitation to the endpoint utilizing the solicitations library:

response = requests.get("https://api.open-notify.org/astros.json")
print(response.status_code)

Output

How to make API calls in Python

Working with JSON Data in Python

JSON (JavaScript Object Notation) is the language of APIs. JSON is a method for encoding information structures that guarantees that they are effectively coherent by machines. JSON is the essential configuration wherein information is passed this way and that to APIs, and most API servers will send their reactions in JSON design. You could have seen that the JSON yield we got from the API seemed as though it contained Python word references, records, strings and numbers. You can consider JSON to be a mix of these items addressed as strings.

Python has incredible JSON support with the json bundle. The json bundle is essential for the standard library, so we don't need to introduce anything to utilize it. We can both believer records and word references to JSON and convert strings to records and word references. On account of our ISS Pass information, it is a word reference encoded to a string in JSON design. The json library has two primary capabilities:

json.dumps() — Takes in a Python item and converts (dumps) it to a string.

json.loads() — Takes a JSON string and converts (loads) it to a Python object.

Example

import json
def jprint(obj):
    # create a formatted string of the Python JSON object
    text = json.dumps(obj, sort_keys=True, indent=4)
    print(text)
jprint(response.json())

Output

How to make API calls in Python

Related Topics

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python pynmea2

Define Pynmea2 Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in...

4 minutes read.

Python callable() Function

Python callable() Function The callable() function returns a boolean value ‘True’ if the specified object is callable, else it returns False. Syntax callable(object) Parameter Object:  The object parameter represents the value to test if it is callable...

1 minute read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

Python Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Python Skyline

Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.