How to Consume REST APIs using Python
API
API stands for Application Programming Interface. API is an interface that acts as a communication layer that makes two application talks to each other.
In order to build API, we use REST( there are other ways like GraphQL ) Architecture Style.
REST
REST stands for Representational State Transfer. REST is an architectural design style that facilitates communication between client and server in the network.
In order to access resources from web services, a request is sent to a specific resource, and a response is expected.
- Resource is any data available in web service.
- Request sent is called an HTTP request.
- HTTP is a protocol that governs how client and server communicate.
- HTTP request uses special methods known as HTTP methods to tell the API which action is needed to be performed.
HTTP Methods
- GET - retrieve an existing resource
- POST - create a new resource
- PUT - update an existing resource
- DELETE - delete a resource
- PATCH - partially update an existing resource
Status Codes
Response from the server is sent after the client makes the request. This response comes with a code that provides information about its results.
The following are common status codes:-
- 200 - OK
- 204 - No Content
- 400 - Bad Request
- 404 - Not Found
- 500 - Internal Server Error
API Endpoints
Referred as public URLs that are used to access resources in web services.
Image Credit:Rapid API
How to Use Python To Consume REST APIs
Userequests
library
To start using it, install by using pip
i.e. pip install requests
Note:- Make sure Python 3 is installed in your machine.
Take an example of JSON Placeholder - a free fake REST API.
import requests
url = "https://jsonplaceholder.typicode.com/posts)"
response = requests.get(url)
print(response.text)
print(response.json())
Here we start importing requests - a de facto library for consuming API.
We assign the endpoint - the actual API to variable url.
Then, we pass the endpoint using the request method in
response = requests.get(url)
.Then you can output using
text
orjson()
method.