can't concat bytes to str: TypeErrorを解決する

コードは以下

def http_post(url, headers, body):
    req = urllib.request.Request(url, body, headers, 'POST')
    try:
        with urllib.request.urlopen(req) as res:
            body = res.read().decode()

でてきたエラーは以下

can't concat bytes to str: TypeError
Traceback (most recent call last):
File "/var/task/sample.py", line xx, in handler
http_post(url, headers, body)
File "/var/task/sample.py", line xx, in http_post
with urllib.request.urlopen(req) as res:
File "/var/lang/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/var/lang/lib/python3.6/urllib/request.py", line 526, in open
response = self._open(req, data)
File "/var/lang/lib/python3.6/urllib/request.py", line 544, in _open
'_open', req)
File "/var/lang/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/var/lang/lib/python3.6/urllib/request.py", line 1361, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/var/lang/lib/python3.6/urllib/request.py", line 1318, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "/var/lang/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/var/lang/lib/python3.6/http/client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/var/lang/lib/python3.6/http/client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/var/lang/lib/python3.6/http/client.py", line 1064, in _send_output
+ b'\r\n'
TypeError: can't concat bytes to str

参考にした記事

stackoverflow.com

分かったこと

・byte型とstring型は結合できないよ、というエラー

じゃあどうしたらいいの?

Stackoverflowの記事を参考にこう直してみた。

def http_post(url, headers, body):
    req = urllib.request.Request(url, json.dumps(body).encode(), headers, 'POST')
    try:
        with urllib.request.urlopen(req) as res:
            body = res.read().decode()

動いたっぽい