python requests post example

Python Requests Post Example

If you are working with APIs, one of the most common things you will need to do is send POST requests. In Python, you can use the requests library to easily send POST requests. Here is an example:

Using Requests Library

To use the requests library, you will first need to install it. You can do this by running pip install requests.

Once you have installed the requests library, you can use it to send a POST request like this:


import requests

url = 'https://example.com/api/users'
data = {"name": "John Doe", "email": "[email protected]"}

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

print(response.status_code)
print(response.json())

In this example, we are sending a POST request to https://example.com/api/users with some data as a dictionary. The response object contains the response from the server. We can access the status code and the JSON response using response.status_code and response.json(), respectively.

You can also send JSON data instead of a dictionary by using the json parameter:


import requests

url = 'https://example.com/api/users'
data = {"name": "John Doe", "email": "[email protected]"}

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

print(response.status_code)
print(response.json())

This will send a POST request with JSON data instead of a dictionary.

Using urllib Library

You can also use the urllib library to send POST requests:


import urllib.request
import urllib.parse
import json

url = 'https://example.com/api/users'
data = {"name": "John Doe", "email": "[email protected]"}
data = json.dumps(data).encode('utf-8')

req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
response = urllib.request.urlopen(req)

print(response.status)
print(response.read().decode('utf-8'))

In this example, we are using the urllib.request library to send a POST request with JSON data. The data parameter is first converted to a JSON string using the json.dumps() function, and then encoded as UTF-8. The request object is created using the Request constructor with the URL, data, and headers as parameters. The response object contains the response from the server. We can access the status code and the response body using response.status and response.read().decode('utf-8'), respectively.

Conclusion

In this article, we have seen how to send POST requests in Python using the requests and urllib libraries. Both methods are easy to use and provide a lot of flexibility.