簡體   English   中英

使用帶有 json 和 python 的 API 獲取請求時收到錯誤

[英]Error received when using an API get request with json and python

當我嘗試執行 API 獲取請求時出現錯誤。 我是新手,所以我知道的不多,而且我不斷收到錯誤消息。 The info for the api is here: https://github.com/aravindasiva/demotivational-quotes-api and the API im using is this https://demotivation-quotes-api.herokuapp.com/graphql The API responce is in一個 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)

在進一步研究您的問題后,我發現了您的問題。 您嘗試使用的 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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM