make a http post request in python

Here's an example of how to make a HTTP POST request in Python using the urllib module:

main.py
import urllib.request
import urllib.parse

url = 'https://www.example.com/api/v1'
data = {'name': 'John Doe', 'email': 'johndoe@example.com'}
data = urllib.parse.urlencode(data).encode('utf-8')  # encode the data as bytes

req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
result = response.read().decode('utf-8')  # decode the response

print(result)
381 chars
13 lines

This example sends a POST request to https://www.example.com/api/v1 with the data {'name': 'John Doe', 'email': 'johndoe@example.com'} in the body of the request. The response is then decoded and printed to the console.

related categories

gistlibby LogSnag