【问题标题】:how to get access to endpoint with API Key through Python requests?如何通过 Python 请求使用 API 密钥访问端点?
【发布时间】:2022-10-17 20:52:53
【问题描述】:

我正在尝试使用 API 密钥访问端点,但我不断收到 401 错误代码。

我正在尝试通过 python 请求库收集内容。

例如:

API Specification

Get list of people

Method GET
Endpoint https://api.json-generator.com/templates/-xdNcNKYtTFG/data
API Key: vza4lbzrzy3cyhg4nbzyjhmqzjlqr2p3qibd9986 (Don't worry. It is a public key.)

Example: Fetch From API by command line

curl --request GET -H "Authorization: Bearer R4iN..." --url https://api.json-generator.com/templates/tAu-9/data

任何人都可以帮忙吗?这是我在 python 中编写的代码:

import requests

url ='https://api.json-generator.com/templates/-xdNcNKYtTFG/data'

api_key='vza4lbzrzy3cyhg4nbzyjhmqzjlqr2p3qibd9986'

headers = {'Authorization' : api_key}

r = requests.get(url,headers=headers)

【问题讨论】:

  • 您的 curl 命令和代码不匹配。注意:标题中的文字Bearer 价值.
  • 不同的 API 需要不同的方法 - 有些在 URL 中需要它,在 POST data 中需要它,在 header 中需要它。您必须显示文档的 URL。
  • 我添加了 curl 示例,因为它解释了一切。

标签: python api rest


【解决方案1】:

您必须将 'Bearer ' 添加到 API 密钥 - 就像在 curl 示例中一样。

headers = {'Authorization' : 'Bearer ' + api_key}

import requests

url ='https://api.json-generator.com/templates/-xdNcNKYtTFG/data'

api_key = 'vza4lbzrzy3cyhg4nbzyjhmqzjlqr2p3qibd9986'

headers = {'Authorization' : f'Bearer {api_key}'}

r = requests.get(url, headers=headers)

data = r.json()

for item in data:
    print(item['name'])

结果:

{'last': 'Pace', 'first': 'Irma'}
{'last': 'Terry', 'first': 'Jaime'}
{'last': 'Wise', 'first': 'Solomon'}
{'last': 'Gutierrez', 'first': 'Alyson'}
{'last': 'Grant', 'first': 'Nieves'}
{'last': 'Mendoza', 'first': 'Sheryl'}
{'last': 'Hardy', 'first': 'Clayton'}
{'last': 'Wong', 'first': 'Deana'}
{'last': 'Parks', 'first': 'Stafford'}
{'last': 'Horton', 'first': 'Melissa'}
{'last': 'Johnston', 'first': 'Nanette'}
{'last': 'Sykes', 'first': 'Sherrie'}
{'last': 'Mckenzie', 'first': 'Monique'}
{'last': 'Coleman', 'first': 'Mccarty'}
{'last': 'Winters', 'first': 'Kelley'}
{'last': 'Barber', 'first': 'Lillie'}
{'last': 'Wright', 'first': 'Knight'}
{'last': 'Fox', 'first': 'Pratt'}
{'last': 'Stewart', 'first': 'Richmond'}
{'last': 'Rose', 'first': 'Erica'}

顺便提一句:

页面CurlConverter.com 可以将curl 命令转换为多种语言的代码——甚至是Python。

【讨论】:

  • 太感谢了!
【解决方案2】:

这就是我在 Javascript 中的做法:

// API KEY const API_KEY ="vza4lbzrzy3cyhg4nbzyjhmqzjlqr2p3qibd9986"

// Object for various requests const request = { fetchUsers: https://api.json-generator.com/templates/-xdNcNKYtTFG/data?access_token=${API_KEY}, };

// Exporting request object. Making it available. export default request;

【讨论】:

    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2020-12-31
    • 2022-01-12
    • 2013-07-04
    • 2021-06-29
    • 2015-08-02
    相关资源
    最近更新 更多