Friday, October 24, 2025
HomeLanguagesPython requests – POST request with headers and body

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.

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.

Headers can be Python Dictionaries like,  { “Name of Header”: “Value of the Header” }

The Authentication Header tells the server who you are.  Typically, we can send the authentication credentials through the Authorization header to make an authenticated request.

Example:

Headers = { “Authorization” : ”our_unique_secret_token” }

response = request.post(“https://example.com/get-my-account-detail”, headers=Headers)

Request Object Structure

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
 
 
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
 
 
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:

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS