×

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

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Get Bounding Box Co-ordinates Python

Python: 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 faster way....

6 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Python Setup guide and installation

Python Installation guide Step by Step Python is widely used high-level programming language. The first version of Python was launched in 1991. Since then, Python has been gaining popularity. It is considered as...

4 minutes read.

Python String swapcase() method

Python String swapcase() method The string.swapcase() method in Python returns a copy of the string with uppercase characters converted to lowercase and vice versa. Syntax string.swapcase() Parameter NA Return This method returns a copy of the string...

1 minute read.

Python String rfind() method

The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found. Syntax string.rfind(sub [,start [,end]]) Parameter sub: This parameter...

2 minutes read.

After Python, What Should I Learn

Python is a programming language used to create websites, software, and other projects. It is easy to code and easy to learn. After learning Python, there are many different directions...

4 minutes read.

Unicode to String in Python

Python 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 faster way....

3 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

How to create a file in Python?

How to create a file in python? Files provide us a convenient way of storing our information. Once we have our data, the next task is to store it so that...

3 minutes read.

How to import pandas in python

How to Install Pandas in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Python Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

GUI Calendar using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

How to Concatenate Two Strings in Python

How to Concatenate Two Strings in Python Like the other data types, operations on strings are quite useful when we deal with some real-life applications. Here we will talk about a simple...

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.

Image to NumPy Arrays in Python

Image is a simple process of working model confined to machine learning, Python works with the image in the data format of width and height i.e. Images are excelled into...

3 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.