事象
下記のようなPythonコードでrequests
でAPIから取得したレスポンスをprint
やreturn
で表示しようとすると、
import requests
r = requests.get(https://api.hoge.com/path?〜)
print(r)
return(r)
下記のような実行結果となり、期待されたJSON形式のレスポンスが取得できない。
# print(r)の結果
<Response [200]>
# return(r)の結果
An error occurred during JSON serialization of response: <Response [200]> is not JSON serializable
Traceback (most recent call last):
File "/var/lang/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/var/lang/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/var/lang/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/var/runtime/awslambda/bootstrap.py", line 134, in decimal_serializer
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Response [200]> is not JSON serializable
解決策
r
ではなくr.text
とする。
import requests
r = requests.get(https://api.hoge.com/path?〜)
print(r.text)
return(r.text)
参考