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 REST API with Python.
If you are a developer (especially a python developer ) and looking for a basic guide to learn how to call rest API in 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 act 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.
Also, One of the 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 info check Wikipedia.
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 E.g.- https://www.university.com/students.
/students is the endpoint, and https://www.university.com/ is the starting URL or base URL.
- Method:- REST APIs provide methods to enable Create, Read, Update, and Delete functionality. The methods used by REST APIs are as follows:-:
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 call rest API in python
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 following steps:-
Install the python requests module with the 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:
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.
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:-
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 a 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() # 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
If we use this we will get the data in raw format and the output will look like this:-
If we use this our data will be in string format and the output will look like this:-
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 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 prints its value.
import requests response = requests.get("https://randomfox.ca/floof") fox_img=response.json() print(fox_img['image'])
So we have got only the 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.
import requests response = requests.get("https://randomfox.ca/floof") fox_img=response.json() print(fox_img['link'])
Here we got only the link as it was the value of the link key.
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.
PIP Package used for Calling Rest API with Python?
pip install requests
Example of HTTP Get Call-in Python?
response = requests.get(“https://randomfox.ca/floof”)
Pingback: Top 66 Senior .NET Developer Interview Questions And Answers
Pingback: GRPC Vs Rest: Important Factors To Consider Before Making A Decision | Beetechnical
Comments are closed