使用 requests 进行 API key 认证
基于 API key 的认证与 Basic Authentication 类似,但您需要在已认证的请求中通过请求头或 URL 参数包含一个唯一的 API key。我们来分别试一试这两种方式。
小提示:
- 已经导入
requests包。 - 使用 API key/token
8apDFHaNJMxy8Kt818aa6b4a0ed0514b5d3进行认证。
本练习是课程的一部分
Python 中的 API 入门
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create a dictionary containing the API key using the correct key-value combination
params = {____: ____}
# Add the dictionary to the requests.get() call using the correct function argument
response = requests.get('http://localhost:3000/albums', ____=params)
if(response.status_code == 200):
print("Success!")
elif(response.status_code == 401):
print('Authentication failed')
else:
print('Another error occurred')