API 使用 python 中的请求模块调用

API Call using request module in python

我不太熟悉 API 调用或请求模块。我正在尝试获取每个 DAO 的关于信息(详细信息)。我正确地得到了 DAO 的名称,但是当我尝试做细节时我得到了 KeyError。任何帮助将不胜感激。

import pandas as pd
import requests

payload = {"requests": [{"indexName": "governance_production", "params": "highlightPreTag=%3Cais-highlight-0000000000%3E&highlightPostTag=%3C%2Fais-highlight-0000000000%3E&hitsPerPage=855&attributesToRetrieve=%5B%22id%22%5D&maxValuesPerFacet=100&query=&page=0&facets=%5B%22types%22%2C%22tags%22%5D&tagFilters="}]}
url = 'https://3b439zgym3-2.algolianet.com/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20JavaScript%20(3.35.1)%3B%20Browser%20(lite)&x-algolia-application-id=3B439ZGYM3&x-algolia-api-key=14a0c8d17665d52e61167cc1b2ae9ff1'
headers = {"content-type": "application/x-www-form-urlencoded"}
req = requests.post(url, headers=headers, json=payload).json()

data = []

for item in req['results'][0]['hits']:
    data.append({
        "name": item['_highlightResult']['name']['value'],
        "details": item['_highlightResult']['details']['value'],
    })

print(data)
df = pd.DataFrame(data)
print(df)

因为在结果 JSON 中不存在名为 details 的键,这就是 returns 错误的原因。

这是您在上面提出的请求的示例 -

它包含 tags 键以及 nametypes

  {
    "_highlightResult": {
      "assetSlug": {
        "matchLevel": "none",
        "matchedWords": [],
        "value": "tribe"
      },
      "name": {
        "matchLevel": "none",
        "matchedWords": [],
        "value": "Fei"
      },
      "tags": [
        {
          "matchLevel": "none",
          "matchedWords": [],
          "value": "DeFi"
        }
      ],
      "types": [
        {
          "matchLevel": "none",
          "matchedWords": [],
          "value": "Protocol"
        }
      ]
    },
    "id": "f9779bc3-4eb4-4830-982b-fc981762dbd8",
    "objectID": "f9779bc3-4eb4-4830-982b-fc981762dbd8"
  }

或不包括 tags

  {
    "_highlightResult": {
      "assetSlug": {
        "matchLevel": "none",
        "matchedWords": [],
        "value": "aave"
      },
      "name": {
        "matchLevel": "none",
        "matchedWords": [],
        "value": "Aave Grants DAO"
      },
      "types": [
        {
          "matchLevel": "none",
          "matchedWords": [],
          "value": "Grants"
        }
      ]
    },
    "id": "b3a88880-b343-4eba-955e-dd0c4970291a",
    "objectID": "b3a88880-b343-4eba-955e-dd0c4970291a"
  }

这里是 JSON 数据的全文 - JSON data