[英]How to get API answer with an API key using the requests package in Python
How to get http request from API organized around REST, JSON is returned by all API responses.如何从围绕 REST 组织的 API 获取 http 请求,所有 API 响应都返回 JSON。 All ressources have support for bulk fetches via "list" API methods
所有资源都支持通过“列表”API 方法进行批量获取
Here is what I have as documentation:这是我的文档:
# With shell, you can just pass the correct header with each request
curl "https://www.api_url.com/api/dispute?page=1&limit=5"
-H "Authorization: [api_key]"
# Query Parameters:
# page 1 The cursor used in the pagination (optional)
#limit 10 A limit on the number of dispute object to be returned, between 1 and 100 (optional).
I don't know how to interpret this in python and to pass api_key to extract the data from this object dispute我不知道如何在 python 中解释这个并通过 api_key 从这个对象争议中提取数据
import requests
import json
response = requests.get("https://api_url.com/")
The -H
option in curl sets a header for the request. curl 中的
-H
选项设置请求的标头。
For a request using requests
, you can set extra headers by passing a keyword argument headers
.对于使用
requests
,您可以通过传递关键字参数headers
来设置额外的标headers
。
import requests
import json
response = requests.get(
"https://www.api_url.com/api/dispute",
headers={"Authorization" : "<api_key_here>"}
)
You can also add your parameters easily if needed如果需要,您还可以轻松添加参数
response = requests.get(
"https://www.api_url.com/api/dispute",
headers={"Authorization" : "<api_key_here>"},
params={
"page": 1,
"limit":1
}
)
If you want to make multiple requests, you can look into using a requests.Session
.如果你想发出多个请求,你可以考虑使用
requests.Session
。 Session Tutorial 会话教程
It will allow you to set the header centrally.它将允许您集中设置标题。
You can also use an Auth Handler to manage authentication.您还可以使用身份 验证处理程序来管理身份验证。
You can use the curlconverter tool to simplify the translation to Python code:您可以使用curlconverter工具来简化到 Python 代码的转换:
For the provided curl
input:对于提供的
curl
输入:
curl "https://www.api_url.com/api/dispute?page=1&limit=5" \
-H "Authorization: [api_key]"
Here is the result in Python.这是 Python 中的结果。 Note that I've changed
params
to a dict
object, as it's easier to work with dictionaries in Python.请注意,我已将
params
更改为dict
对象,因为在 Python 中使用字典更容易。 It doesn't matter if the values for any of the query params are a type other than str
, as they will simply be concatenated in the URL string when making the request.任何查询参数的值是否是
str
以外的类型都没有关系,因为它们将在发出请求时简单地连接在 URL 字符串中。
import requests
headers = {
'Authorization': '[api_key]',
}
params = {
'page': 1,
'limit': 5
}
response = requests.get('https://www.api_url.com/api/dispute',
headers=headers, params=params)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.