Ecobee API:文档用于 curl 不确定如何转换为 Python
Ecobee API: Documentation is for curl not sure how to translate to Python
Ecobee API 文档显示这是访问其 API:
的一种方式
#curl -s -H 'Content-Type: text/json' -H 'Authorization: Bearer AUTH_TOKEN' 'https://api.ecobee.com/1/thermostat?format=json&body=\{"selection":\{"selectionType":"registered","selectionMatch":"","includeRuntime":true\}\}'
我在 curl 中使用了该代码,它似乎有效。
但是,当我尝试我认为等效的 python 代码时,它不起作用。
(我真的一点都不了解 curl。我从几个小时的互联网研究中了解到的。)
我使用的代码:
import requests
headers = {"Content-Type": "text/json", "Authorization": "Bearer AUTH_TOKEN"}
response = requests.get('https://api.ecobee.com/1/thermostat?format=json&body=\{"selection":\{"selectionType":"registered","selectionMatch":"","includeRuntime":"true"\}\}', headers=headers)
print(response.text)
当我发送这个时,我得到:
{
"status": {
"code": 4,
"message": "Serialization error. Malformed json. Check your request and parameters are valid."
}
}
不确定我的 json 格式有什么问题。任何帮助深表感谢。
您需要 URL-escape 参数中的特殊字符。
手动执行此操作可能很麻烦并且容易出错。我不是 Python 专家,但初步研究建议使用 Python 的 request.get()
内置的 params
选项。例如:
import requests
url = 'https://api.ecobee.com/1/thermostat'
TOKEN = 'ECOBEEAPIACCESSTOKEN'
header = {'Content-Type':'text/json', 'Authorization':'Bearer ' + TOKEN}
payload = {'json': '{"selection":{"selectionType":"registered","selectionMatch":"","includeRuntime":"true"}}'}
response = requests.get(url, params=payload, headers=header)
print(response.url)
print(response.text)
Ecobee API 文档显示这是访问其 API:
的一种方式#curl -s -H 'Content-Type: text/json' -H 'Authorization: Bearer AUTH_TOKEN' 'https://api.ecobee.com/1/thermostat?format=json&body=\{"selection":\{"selectionType":"registered","selectionMatch":"","includeRuntime":true\}\}'
我在 curl 中使用了该代码,它似乎有效。 但是,当我尝试我认为等效的 python 代码时,它不起作用。
(我真的一点都不了解 curl。我从几个小时的互联网研究中了解到的。)
我使用的代码:
import requests
headers = {"Content-Type": "text/json", "Authorization": "Bearer AUTH_TOKEN"}
response = requests.get('https://api.ecobee.com/1/thermostat?format=json&body=\{"selection":\{"selectionType":"registered","selectionMatch":"","includeRuntime":"true"\}\}', headers=headers)
print(response.text)
当我发送这个时,我得到:
{
"status": {
"code": 4,
"message": "Serialization error. Malformed json. Check your request and parameters are valid."
}
}
不确定我的 json 格式有什么问题。任何帮助深表感谢。
您需要 URL-escape 参数中的特殊字符。
手动执行此操作可能很麻烦并且容易出错。我不是 Python 专家,但初步研究建议使用 Python 的 request.get()
内置的 params
选项。例如:
import requests
url = 'https://api.ecobee.com/1/thermostat'
TOKEN = 'ECOBEEAPIACCESSTOKEN'
header = {'Content-Type':'text/json', 'Authorization':'Bearer ' + TOKEN}
payload = {'json': '{"selection":{"selectionType":"registered","selectionMatch":"","includeRuntime":"true"}}'}
response = requests.get(url, params=payload, headers=header)
print(response.url)
print(response.text)