API request with Python
What is API ?
Application Programming Interface (API) is an application interface that allows two applications to communicate each other. Creating API is creating routes(endpoint and parameter) and response back some data. Means that other application can use our service with requesting API. RESTFul (Representational state transfer) is style or rules of creating APIs.
Example of API and HTTP request, response
For example, there is application A and application B. Application A wants weather forecast data to show user the weather data in application. Application B have weather data and create some routes(api routes) to allow other application to use weather data(services). Then application A request application B (creating HTTP request) and application B response back requested weather data to application A. Then application A can use data to show user the weather data in application.
API requests
- using python requests module
- request data from jsonplaceholder
request method ➜ get (request.get)
url ➜ https://jsonplaceholder.typicode.com/posts
import requestsresponse=requests.get("https://jsonplaceholder.typicode.com/posts")response_data = response.json()print(response_data)
Endpoint and parameters
request user with Sincere@april.biz email from jsonplaceholder
https://jsonplaceholder.typicode.com/users?email=Sincere@april.biz
simple request
import requestsresponse=requests.get("https://jsonplaceholder.typicode.com/users?email=Sincere@april.biz")response_data = response.json()print(response_data)
Using params argument
Endpoint ➜ https://jsonplaceholder.typicode.com/users
parameters ➜ email=Sincere@april.biz
import requestsresponse=requests.get("https://jsonplaceholder.typicode.com/users", params={"email":"Sincere@april.biz"})response_data = response.json()print(response_data)