Reputation: 2143
I am trying to send a POST
request. For this request, I want to send a JSON
in the body but this is not working and it gives an error saying: can't concat str to bytes
. What is the correct way to submit a POST
request with a JSON
body?
import http.client, urllib.parse
def update_status(status, versionId):
conn = http.client.HTTPConnection(server_ip, server_port)
body = {
"status": status,
"id": versionId
}
print("body:", body)
headers = {"Content-type": "application/json"}
conn.request("POST", "", body, headers)
response = conn.getresponse()
print("response status:", response.status)
print("response reason:", response.reason)
return response
return update_status
Upvotes: 0
Views: 482
Reputation: 101
You need to serialize data first.
data = json.dumps(body)
data = data.encode('utf8')
conn.request("POST", "", data, headers)
Upvotes: 0
Reputation: 1470
Consider using requests module. As easy as it looks below:
import requests
body = {"key": "value"}
response = requests.post("http://<SOME_URL>", json=body)
Upvotes: 1