HomeContact
Python
Simple POST with python requests
Karthikeya
February 27, 2021
1 min

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

REQUEST BODY:

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
}

CODE:

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())
  • variable url contains the post end point
  • body contains the request body to be sentence
  • post() method is used to send post request with request body sent in data argument.
  • finally, we print the status code and response json to the console.

OUTPUT

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'
}

Related Posts

Deep comparison of JSON in python
November 18, 2021
1 min
© 2021, All Rights Reserved.

Quick Links

About UsContact UsSite Map

Social Media