Request with body

POST requests pass their data through the message body, The Payload will be set to the data parameter. data parameter takes a dictionary, a list of tuples, bytes, or a file-like object. You’ll want to adapt the data you send in the body of your request to the specified URL.

Syntax:

requests.post(url, data={key: value}, json={key: value}, headers={key:value}, args) *(data, json, headers parameters are optional.)

Given below are few implementations to help understand the concept better.

Example 1: Sending requests with data as a payload

Python3




import requests
 
url = "https://httpbin.org/post"
 
data = {
    "id": 1001,
    "name": "geek",
    "passion": "coding",
}
 
response = requests.post(url, json=data)
 
print("Status Code", response.status_code)
print("JSON Response ", response.json())


Output:

Example 2: Sending requests with JSON data and headers

Python




import requests
import json
 
url = "https://httpbin.org/post"
 
headers = {"Content-Type": "application/json; charset=utf-8"}
 
data = {
    "id": 1001,
    "name": "geek",
    "passion": "coding",
}
 
response = requests.post(url, headers=headers, json=data)
 
print("Status Code", response.status_code)
print("JSON Response ", response.json())


Output:



Python requests – POST request with headers and body

HTTP headers let the client and the server pass additional information with an HTTP request or response. All the headers are case-insensitive, headers fields are separated by colon, key-value pairs in clear-text string format.

Similar Reads

Request with headers

Requests do not change its behavior at all based on which headers are specified. The headers are simply passed on into the final request. All header values must be a string, bytestring, or Unicode. While permitted, it’s advised to avoid passing Unicode header values. We can make requests with the headers we specify and by using the headers attribute we can tell the server with additional information about the request....

Request with body

POST requests pass their data through the message body, The Payload will be set to the data parameter. data parameter takes a dictionary, a list of tuples, bytes, or a file-like object. You’ll want to adapt the data you send in the body of your request to the specified URL....