使用Python向ThingsBoard发送遥测数据时遇401未授权错误
ThingsBoard API发送遥测数据401错误排查
我尝试通过API向ThingsBoard发送遥测数据,但发起请求时遇到了401错误码。使用的Python脚本如下:
import requests import time import json server = "https://demo.thingsboard.io" access_token = "Qk78CWpafxj4NB2TzGXz" entity_id = "f6fa1e60-a078-11ed-bed1-3ba75184734b" def send_active(server, access_token, entity_id, msg): headers = { "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } url = f"{server}/api/v1/{entity_id}/telemetry" payload = { "ts": int(time.time() * 1000), "values": { "message": msg } } response = requests.post(url, headers=headers, data=json.dumps(payload)) if response.status_code != 204: print("Request headers:", response.request.headers) print("Request body:", response.request.body) print("Request failed with status code:", response.status_code) print("Response content:", response.content) raise Exception("Failed to send telemetry data") msg = "active" send_active(server, access_token, entity_id, msg)
得到的错误信息如下:
Request headers: {'User-Agent': 'python-requests/2.27.1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Authorization': 'Bearer Qk78CWpafxj4NB2TzGXz', 'Content-Length': '51'} Request body: b'{"ts": 1676028720, "values": {"message": "active"}}' Request failed with status code: 401 Response content: b''
问题分析与修正方案
API端点路径错误
ThingsBoard的v1遥测上传API不需要在URL中传入entity_id,正确的端点格式是/api/v1/{access_token}/telemetry,直接用设备的access token作为路径参数来认证设备身份。你当前的URL用了entity_id,导致认证失败。认证方式混用
v1 API仅通过URL中的access token完成设备认证,不需要在请求头中添加Authorization: Bearer {access_token}。你同时使用了两种认证逻辑,反而触发了权限校验失败。修正后的脚本
调整URL和请求头,修改后的代码如下:
import requests import time import json server = "https://demo.thingsboard.io" access_token = "Qk78CWpafxj4NB2TzGXz" def send_active(server, access_token, msg): headers = { "Content-Type": "application/json" } # 修正API URL,用access_token替换entity_id url = f"{server}/api/v1/{access_token}/telemetry" payload = { "ts": int(time.time() * 1000), "values": { "message": msg } } response = requests.post(url, headers=headers, data=json.dumps(payload)) if response.status_code != 204: print("Request headers:", response.request.headers) print("Request body:", response.request.body) print("Request failed with status code:", response.status_code) print("Response content:", response.content) raise Exception("Failed to send telemetry data") else: print("遥测数据发送成功") msg = "active" send_active(server, access_token, msg)
关键修改点说明
- 删除了
entity_id参数,因为v1 API不需要该值 - 调整API URL,将路径中的
entity_id替换为设备的access_token - 移除请求头中的
Authorization字段,避免认证逻辑冲突
运行修正后的脚本,若返回204状态码,则说明遥测数据已成功上传到ThingsBoard。
内容的提问来源于stack exchange,提问作者JohnEspinosa
相关产品推荐
相关产品推荐

