HTTP POST is mainly used to create new resource at the backend. The resource can be anything from a new user to a new product. POST maps to “CREATE” part of database CRUD operations. More on CRUD operations here
For the purpose of simple POST request, we will use POST API exposed by jsonplaceholder. The endpoint we are intersted in is,
https://jsonplaceholder.typicode.com/posts
Since we are creating a new resource, in this case a new post, we have to pass the information of the new resource while making the API call. This is done through request body. A sample request body for the endpoint looks like this
{ "title" : "Make a POST call", "body" : "Details of making post call ....", "userId": 1 }
import requests from pprint import pprint url = "https://jsonplaceholder.typicode.com/posts" body = { "title" : "Make a POST call", "body" : "Details of making post call ....", "userId": 1 } response = requests.post(url, data=body) print(response.status_code) pprint(response.json())
url
contains the post end pointbody
contains the request body to be sentencepost()
method is used to send post request with request body sent in data
argument.As a best practice, successfull post call returns status code 201 but some APIs just return 200.
As long as the status code is in 2XX
series, it should be fine.
201 { 'body': 'Details of making post call ....', 'id': 101, 'title': 'Make a POST call', 'userId': '1' }
Quick Links
Legal Information
Social Media