LoginSignup
16
7

More than 3 years have passed since last update.

【Python】requestsで取得したAPIからのレスポンスが「<Response [200]>」となる

Posted at

事象

下記のようなPythonコードでrequestsでAPIから取得したレスポンスをprintreturnで表示しようとすると、

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)

参考

16
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
7