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 its data accessible to third-party applications.
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 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 which 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:
- 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. - 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 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>"
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
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.
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.
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.
Other HTTP code tables are as follows:
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:
The content of the request can be accessed in a few ways such as:
response.content()
response.text()
response.json()
response.content()
If we use this, we will get the data in raw format and the output will look like this:
response.text()
If we use this, our data will be in string format and the output will look like this:
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:
Import requests
response = requests.get("https://randomfox.ca/floof")
print(response.json())
You will get the following output:
Click on the link and you will be redirected to a random fox image like the following:
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
import requests
response = requests.get("https://randomfox.ca/floof")
fox_img=response.json()
print(fox_img['image'])
Output
So we have got only string
that links to our image and not the whole dictionary.
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
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.
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 to any of your projects to do wonders.
History
- 4th December, 2021: Initial version