【问题标题】:Error received when using an API get request with json and python使用带有 json 和 python 的 API 获取请求时收到错误
【发布时间】:2022-01-12 04:44:09
【问题描述】:

当我尝试执行 API 获取请求时出现错误。我是新手,所以我知道的不多,而且我不断收到错误消息。 api 的信息在这里:https://github.com/aravindasiva/demotivational-quotes-api,我使用的 API 是这个https://demotivation-quotes-api.herokuapp.com/graphql API 响应位于 json 数组中,我试图从中提取特定信息。任何帮助表示赞赏。

import requests
import json

def get_quote():
  response = requests.get('https://demotivation-quotes-api.herokuapp.com/graphql')
  json_data = json.loads(response.text)
  quote = json_data[0]['quote'] + " -" + json_data[0]['author']
  return(quote)


quote = get_quote()
print(quote)


错误:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    quote = get_quote()
  File "main.py", line 6, in get_quote
    json_data = json.loads(response.text)
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

【问题讨论】:

  • 做 repr(response.text) 或 print("{}".format(response.text)) 你会看到问题。我不是pythonist,也许直接打印(response.text)也可以
  • 当我尝试这些解决方案中的每一个时,我都会收到相同的错误: Traceback (last last call last): File "main.py", line 12, in print(response.text) NameError:名称“响应”未定义
  • 你找到了问题......没有 response.text 这样的东西。现在对响应使用相同的方法,看看你有什么
  • 我不太明白你的意思?

标签: python json python-requests


【解决方案1】:

在进一步调查您的问题后,我发现了您的问题。您尝试使用的 api 期待发布请求,而不是获取请求。然后它期待一个包含 API 查询的有效负载,以便找到您正在寻找的报价。

您想使用requests.post() 方法。

这应该足以为您指明正确的方向,我建议您查看一些有关如何使用 requests 以及不同 HTTP 方法的区别的教程。


我认为您的问题是您的回复不包含文本数据。也许它会返回一个 json?尝试像这样打印您的响应 json

print(response.json())

您也可以尝试直接打印response.text 以确认它是None

在您尝试将其解析为您的 json.loads 方法之前验证响应。

编辑:

试试这个

import requests

response = requests.get('https://demotivation-quotes-api.herokuapp.com/graphql')

print(response.status_code)
print(response.json())

【讨论】:

  • 我尝试了你的新解决方案,我得到了这个作为响应:400 > 的绑定方法 Response.json>> 我接下来应该做什么?
  • 查看我的编辑。你到底想做什么?
  • 我正在尝试从该站点获取信息,并将其格式化为打印,使其显示为引用,然后显示为作者。
  • 好的,我想我明白你在说什么了。您对如何设置发布请求有任何想法吗?
猜你喜欢
  • 2022-01-07
  • 2017-09-12
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 2014-06-11
  • 2021-05-12
  • 1970-01-01
相关资源
最近更新 更多