S Andrew
S Andrew

Reputation: 7268

Can't concatenate str to bytes error while posting data to api in Python

I have post api url as below:

https://az-us-eu-dev-sgtps-apilayer.azurewebsites.net/api/HttpTrigger1?code=sqEdwsf6vapdcPnI9zxwlwXHw==

I am posting json data to it and I am getting proper response with code 200.

I have to do the same from python and I am using below code:

headers = {'Content-Type': 'application/json'}

conn = http.client.HTTPSConnection('az-us-eu-dev-sgtps-apilayer.azurewebsites.net')

conn.request("POST", "/api/HttpTrigger1?code=sqEdwsf6vapdcPnI9zxwlwXHw==", jdata, headers)
response = conn.getresponse()
rdata = response.read()
rdata = rdata.decode('utf8')
rdata = json.loads(rdata)

but on 3rd line above, I am getting below error:

can't concat str to bytes

I tried doing this:

url = "/api/HttpTrigger1?code=sqEdwsf6vapdcPnI9zxwlwXHw=="
new_url = str.encode(url)
conn.request("POST", new_url, jdata, headers)

Below is the jdata which is json data to be posted to the api url:

{
    "reqType": "True",
    "date": "27-09-2019"
}

But it shows same error. How can I resolve it?

Upvotes: 1

Views: 2778

Answers (1)

han solo
han solo

Reputation: 6590

You could use the requests module like,

>>> import requests
>>> import json
>>> endpoint = 'https://az-us-eu-dev-sgtps-apilayer.azurewebsites.net/api/HttpTrigger1?code=sqEdwsf6vapdcPnI9zxwlwXHw=='
>>> jdata = {"reqType": "True", "date": "27-09-2019"}
>>> headers = {'Content-Type': 'application/json'}
>>> r = requests.post(endpoint, data=json.dumps(jdata), headers=headers)

Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:

>>> r = requests.post(endpoint, json=jdata, headers=headers)
>>> r.json() # for response

Upvotes: 1

Related Questions