pythonrequests.com

Tutorials /

post request python form data

· 1 min read · Bugs · Troubleshooting

Post Request Python Form Data

If you are working with a web application, you will often need to send data from the client side to the server side. One common way to do this is through a POST request. In Python, you can send a POST request with form data using the requests library.

Using the requests library

First, you need to install the requests library. You can do this using pip:

pip install requests

Once you have the requests library installed, you can use it to send a POST request with form data. Here is an example:

import requests

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

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

print(response.text)

In this example, we are sending a POST request to 'http://example.com/api' with the form data {'key1': 'value1', 'key2': 'value2'}. The response from the server is then printed to the console.

You can also send JSON data instead of form data by passing a JSON object to the json parameter of the post method:

import requests

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

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

print(response.text)

In this example, we are sending a POST request to 'http://example.com/api' with the JSON data {'key1': 'value1', 'key2': 'value2'}. The response from the server is then printed to the console.

Overall, the requests library makes it easy to send POST requests with form data or JSON data in Python.

More tutorials