python requests post parameters

Python Requests Post Parameters

When it comes to sending data to a server, there are two common HTTP methods: GET and POST. The GET method sends parameters in the URL, while the POST method sends them in the body of the request.

Using Python Requests Library

Python's Requests library is a popular tool for making HTTP requests. To send a POST request with parameters using Requests, you can use the post() method and pass the parameters as a dictionary:


import requests

url = 'https://example.com/api'
payload = {'key1': 'value1', 'key2': 'value2'}

response = requests.post(url, data=payload)

print(response.text)

In this example, we create a dictionary payload with two key-value pairs. We then pass this dictionary as the data argument to post(). The response variable contains the server's response.

Using JSON Data

You can also send data in JSON format by passing a dictionary to the json argument instead:


import requests

url = 'https://example.com/api'
payload = {'key1': 'value1', 'key2': 'value2'}

response = requests.post(url, json=payload)

print(response.text)

This sends the same data as in the previous example, but in JSON format instead of form-encoded data. Note that the json argument automatically sets the Content-Type header to application/json.

Using Custom Headers

You can also include custom headers in the request by passing a dictionary to the headers argument:


import requests

url = 'https://example.com/api'
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'X-My-Header': 'value'}

response = requests.post(url, json=payload, headers=headers)

print(response.text)

This sends the same data as in the previous example, but with a custom header X-My-Header.

Conclusion

Sending POST requests with parameters in Python using the Requests library is easy and can be done in a variety of formats. Whether you're sending form-encoded data or JSON, Requests makes it simple to send data to a server and receive its response.