API
API stands for Application Programming Interface.
API is an interface that acts as communication layer which 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 response is expected.
- Resource is any data available in web service.
- Request sent is called HTTP request.
- HTTP is a protocol which governs how client and server communicate.
- HTTP request uses special methods known 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 server is sent after client making request. This response comes with a code which provides the information about the it's 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
Take example of Quotes from Rapid API.
import requests
url = "https://quotes15.p.rapidapi.com/quotes/random/"
headers = {
'x-rapidapi-host': "quotes15.p.rapidapi.com",
'x-rapidapi-key': "b799b564e4mshe9022c63f6e7e49p12a6bbjsndfd08f1175da"
}
response = requests.request("GET", url, headers=headers)
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.
~ headers are extra information for each API call you can make. (don't worry - they come with API documentation)
~ Then, we pass the endpoint using request method in
response = requests.request("GET", url, headers=headers)
~ Then you can output using text
or json()
method.
Top comments (0)