python requests url encode body

Python Requests URL Encode Body

URL encoding is a process of converting data into a format that can be transmitted over the internet. Python requests module is used for sending HTTP requests in Python. When sending data in the body of an HTTP request, it is important to encode it properly so that the server can understand it. In this blog, we will learn how to URL encode the data in the body of an HTTP request using Python requests module.

Method 1: Using urlencode() function from urllib.parse module

The urlencode() function from the urllib.parse module can be used to encode a dictionary of key-value pairs into a URL-encoded string. Here is an example:


import requests
from urllib.parse import urlencode

url = 'https://example.com/api/v1/some-endpoint'
data = {'name': 'John Doe', 'age': 30}

response = requests.post(url, data=urlencode(data), headers={'Content-Type': 'application/x-www-form-urlencoded'})

print(response.content)

In the above code, we have first imported the requests module and urlencode() function from the urllib.parse module. Then, we have defined the URL of the endpoint and the data that we want to send in the body of the request as a dictionary. We have then used the urlencode() function to convert the dictionary into a URL-encoded string and passed it as data to the requests.post() method. We have also set the Content-Type header to 'application/x-www-form-urlencoded' to indicate that we are sending URL-encoded data in the body of the request.

Method 2: Using json.dumps() function from json module

If we want to send data in JSON format, we can use the json.dumps() function from the json module to convert a dictionary of key-value pairs into a JSON-encoded string. Here is an example:


import requests
import json

url = 'https://example.com/api/v1/some-endpoint'
data = {'name': 'John Doe', 'age': 30}

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

print(response.content)

In the above code, we have imported the requests module and json module. We have defined the URL of the endpoint and the data that we want to send in the body of the request as a dictionary. We have then used the json.dumps() function to convert the dictionary into a JSON-encoded string and passed it as data to the requests.post() method. We have also set the Content-Type header to 'application/json' to indicate that we are sending JSON data in the body of the request.