首页 > 解决方案 > appending input to the end of api call in python

问题描述

def i(bot,update,args):
    coin=args
    infoCall =requests.get("https://api.coingecko.com/api/v3/coins/").json()
    coinId = infoCall ['categories']
    update.message.reply_text(coinId)

I would like to add to the end of the api request the args declared in coins=args so that it retrieves the info my user requests but this is the error i get

coinId = infoCall ['categories']
KeyError: 'categories'

which my guess is because its not formating the request correctly so the api is giving a 404 and not the info being requested

def i(bot,update,args):
    coin=args
    infoCall =requests.get("https://api.coingecko.com/api/v3/coins/").json()
    infoCall = json.loads(infoCall)+str(coins) 
    coinId = infoCall['categories']
    update.message.reply_text(str (coinId))

after adding this, this is the new error i get

    Traceback (most recent call last):
  File "C:\Users\Matthew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telegram\ext\dispatcher.py", line 279, in process_update
    handler.handle_update(update, self)
  File "C:\Users\Matthew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telegram\ext\commandhandler.py", line 173, in handle_update
    return self.callback(dispatcher.bot, update, **optional_args)
  File "C:/Users/Matthew/Desktop/coding_crap/CryptoBotBetav2.py", line 78, in i
    infoCall = json.loads(infoCall)+str(coins)
  File "C:\Users\Matthew\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 341, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not list

标签: pythonjsonbotstelegram

解决方案


基本上,您没有将args参数附加到 api 点,这就是您收到错误的原因。您需要'bitcoin'在发出请求之前将 附加到 api 点,而不是在输出上。一个典型的例子如下。我已经删除了更新和其他未使用的变量。您可以根据需要放置它们。

import requests
def i(args):
    coin=args
    infoCall =requests.get("https://api.coingecko.com/api/v3/coins/"+ args).json()
    coinId = infoCall ['categories']
    print(coinId)
    # update.message.reply_text(coinId)
i('bitcoin')

输出:

['加密货币']


推荐阅读