Click here to Skip to main content
15,180,249 members
Articles / Programming Languages / Python
Article
Posted 4 Dec 2021

Tagged as

Stats

4.4K views
8 bookmarked

How to Use Rest API with Python

Rate me:
Please Sign up or sign in to vote.
4.54/5 (4 votes)
4 Dec 2021CPOL6 min read
Step by step guide to consuming the Rest API endpoints using Python programming
Most of the web services in today’s digital world make their data accessible to third-party applications through an application programming interface (API). To build these APIs, we need some architecture style. REST is one of the most popular architecture styles to build APIs and Python is probably the best choice to get data from REST APIs and also for building our own Python REST APIs.

Introduction

If you are a developer (especially a Python developer) and looking for a basic guide to learn how to use Rest API with Python, then you have landed in the right place where you will learn about Rest API with Python in a very simple way.

What are APIs?

API is the acronym for Application Programming Interface. The API acts as an interface by which one application makes their data accessible to third-party applications.

what is API

The most common use of APIs is to retrieve data from remote websites, by making a request that is used all over the web. The most common API usages that we all see every day is “log-in using Facebook (Facebook Login API)/Twitter/Google/Github”. Instead of directly logging in to users’ social media accounts, applications use APIs to authenticate the user with each login.

What is a REST Architecture

Rest Architecture diagram

REST stands for Representational state transfer which is a software architectural style of APIs for web services. REST consists of a set of constraints designed to simplify software architecture for Client/Server communication.

Some of the architectural constraints of REST are as follows:

  • Stateless: The server won’t maintain any data from the requests coming from the client-side. The session state is stored only on the client-side.
  • Client-server: The client who is responsible for the user interface, and the server who is responsible for the backend and data storage must be independent of each other.
  • Cacheable: The data that will be retrieved from the server must be cacheable either by the client or by the server.
  • Uniform interface: A uniform interface should be provided by the server for accessing resources without defining their representation.
  • Layered system: The client may indirectly access the resources present on the server via other layers such as a proxy or load balancer.

For more information, check Wikipedia.

REST APIs

We already discussed that APIs are used to retrieve data from remote websites. But the question is how do we make a request to a remote web server and retrieve data? Well, that is done by making use of the URL endpoint that is where the API is being served from where each URL is called an HTTP request and the data that gets sent back is called a response.

The HTTP Request

The HTTP Request consists of the following components:

  1. Endpoint: The URL that indicates what data you are interacting with. The root endpoint is the starting point of the API from where the user is requesting. For example, https://www.university.com/students.
    /students is the endpoint, https://www.university.com/ is the starting URL.
  2. Method: REST APIs provide methods to enable Create, Read, Update, and Delete functionality. The methods used by REST APIs are as follows:
    • GET – Retrieve data
    • PUT – Replace data
    • POST – Create data
    • DELETE – Delete data

The Response

For every request, a response will be received from the API.

For an example: The curl command on the terminal can be used to make a GET request to the Open Notify API that gives information about astronauts who are currently in space:

curl -X GET "<a href="http://api.open-notify.org/astros.json">http://api.open-notify.org/astros.json</a>"

Rest API get request response using curl

Above, you can see a response in JSON format that gives the data about those astronauts.

How to Use Python Requests with REST APIs

Now, let’s understand how you can integrate with a REST API using Python Requests. Firstly, make sure you have Python and pip installed on your host machine. (In this tutorial, I am using Linux) and after that, follow the steps given below:

Step 1: Install the Python Requests Module with pip Command on Your Terminal

pip install requests

install python packages

Now you can start using Python Requests for interacting with a REST API, you should import the Requests library into that particular Python script that you want to use it in:

import requests

Step 2: Next, you have to Request Data With GET

The GET method is used to retrieve data for any resources we are interested in from a REST API. Here, we are going to work with https://randomfox.ca/, which will give you a random picture of little foxes each time.

randomfox.ca rest api example

Copy the API from the website

We have to create an object or variable that’s going to store all the content that we will get from the above website’s server in response to the GET request, including headers and the data payload.

C#
response = requests.get("https://randomfox.ca/floof")
print(response.status_code)

You can access a lot of things from the object among which the line print(response.status_code) will return a status code whenever you are going to make HTTP requests that will inform you how the request went. The Default is 200 or “Ok” which means the response went well and all the information returned is fine.

python main file

Other HTTP code tables are as follows:

Rest API status codes with description

Step 3: Retrieve the Data You Want To (Here, the Random Pic of the Fox)

So now, we are going to use the JSON function which is a part of the request. All or most of the APIs use a language called JSON (somewhat looks like Python dictionary) which is a type of standard to communicate with API information which will be in the same format as given on the website:

Image 8

The content of the request can be accessed in a few ways such as:

C#
response.content() # Return raw bytes of data payload

response.text()    # Return string representation of data payload,
                   # as it is string we can’t pull any data

response.json()    # Convenient when the API returns JSON

response.content()

If we use this, we will get the data in raw format and the output will look like this:

Image 9

response.text()

If we use this, our data will be in string format and the output will look like this:

Image 10

response.json()

So to get what we need, i.e., the random fox picture we have to use the JSON function. We have to replace our print(response.status_code) (from step 2) with the print(response.text()) and our final code will look like the following:

C#
Import requests
response = requests.get("https://randomfox.ca/floof")
print(response.json())

You will get the following output:

Image 11

Click on the link and you will be redirected to a random fox image like the following:

Image 12

Alternate Way / Another Method

When we are printing with JSON, we’re actually working with a dictionary. So we can create a new variable (fox_img) and set it with response.json(). This response.json() will get the dictionary and put it in the new variable(fox_img) from where now we can take any of the data and print it out.

For example: We have two keys “image” and “link” that we can use to modify our code like the following:

Using Image Key

As we have used the image key, the API will go and look for the image key in the dictionary and print its value.

Code
C#
import requests
response = requests.get("https://randomfox.ca/floof")
fox_img=response.json()
print(fox_img['image'])
Output

So we have got only the string that links to our image and not the whole dictionary.

Image 13

Image 14

Using Link Key

Here, we have used the link key so the API will now go and look for the link key in the dictionary and prints its value.

Code
C#
import requests
response = requests.get("https://randomfox.ca/floof")
fox_img=response.json()
print(fox_img['link'])

Output:

Here, we got only the link as it was the value of the link key.

Image 15

Image 16

Conclusion

This was a very short and beginner-friendly tutorial to give you a basic idea of how you can use Rest API with Python, you can do a lot more things with APIs. Once you get the data, you can use it in your own way and apply it on any of your projects to do wonders.

History

  • 4th December, 2021: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

dk_the_developer
https://beetechnical.com
India India
I'm a lead developer/architect located in Bangalore(silicon valley of India) with 10 years of experience in C#,Asp.Net, PHP software projects. Trying to get expertise in Test-driven development, Domain-driven development.

Comments and Discussions

 
QuestionMessage Closed Pin
31-Dec-21 1:53
Memberrishab sain31-Dec-21 1:53 
QuestionThanks For Sharing Pin
Mantra Care6-Dec-21 23:53
professionalMantra Care6-Dec-21 23:53 
GeneralMy vote of 3 Pin
Mantra Care6-Dec-21 23:47
professionalMantra Care6-Dec-21 23:47 
QuestionPython? Pin
Member 123643906-Dec-21 7:33
MemberMember 123643906-Dec-21 7:33 
QuestionCacheable, sorry plain wrong Pin
0x01AA5-Dec-21 8:59
professional0x01AA5-Dec-21 8:59 
GeneralMy vote of 5 Pin
Richard MacCutchan4-Dec-21 5:20
mveRichard MacCutchan4-Dec-21 5:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.