python requests post headers body

Python Requests Post Headers Body

Python Requests is a popular library used for making HTTP requests in Python. It allows you to easily send HTTP/1.1 requests using Python, and supports a variety of different methods, including GET, POST, PUT, DELETE, and more.

HTTP POST Request

HTTP POST request is used to send data to the server. In Python Requests library, we can make a POST request using the requests.post() method. When making a POST request, we can include additional data in the request body and headers.

Syntax


import requests

url = 'http://example.com'
headers = {'Content-type': 'application/json'}
data = {'key1': 'value1', 'key2': 'value2'}

response = requests.post(url, headers=headers, json=data)
print(response.json())
  • url: The URL to which the request is being sent.
  • headers: Dictionary of HTTP Headers to send with the request.
  • data: Dictionary, list of tuples or bytes to send in the body of the request.
  • response: Response object containing server's response to the request.

Headers

Headers are additional information sent along with the request. They contain metadata about the request, such as the content type, user agent, and more. In Python Requests library we can pass headers as a dictionary using the headers parameter.


headers = {'Content-type': 'application/json'}
response = requests.post(url, headers=headers, json=data)

Body

The request body contains the data that is being sent to the server. In Python Requests library we can pass data as a dictionary, list of tuples or bytes using the json parameter.


data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, headers=headers, json=data)

Multiple Ways to Send Data in Post Request

In Python Requests library we can send data in different formats such as JSON, XML or form-encoded data.

JSON Data


import json

headers = {'Content-type': 'application/json'}
data = {'key1': 'value1', 'key2': 'value2'}
json_data = json.dumps(data)

response = requests.post(url, headers=headers, data=json_data)

XML Data


headers = {'Content-type': 'text/xml'}
xml_data = '<?xml version="1.0" encoding="UTF-8"?><root><key1>value1</key1><key2>value2</key2></root>'

response = requests.post(url, headers=headers, data=xml_data)

Form-Encoded Data


headers = {'Content-type': 'application/x-www-form-urlencoded'}
data = {'key1': 'value1', 'key2': 'value2'}
form_data = urllib.parse.urlencode(data)

response = requests.post(url, headers=headers, data=form_data)