使用Sheety API更新Google Sheet时PUT请求400错误求助
Sheety API PUT请求授权错误排查与解决
我在使用Sheety API向Google Sheet发送PUT请求更新数据时,收到400 Client Error: Bad Request for url错误,错误详情提示:
Unauthorized. A valid 'Authorization' header is required to access this API.
但GET请求使用相同的请求头能正常获取数据,且未超出Sheety API的请求限额,仅无法更新或编辑表格行。
相关代码
Data Manager类代码
import requests from pprint import pprint class DataManager: # This class is responsible for talking to the Google Sheet. def __init__(self): self.sheety_api = "https://api.sheety.co/e7247c0056fb99617ecc3140adf89a40/flightTrackerData/data" self.sheety_token = "YOUR TOKEN" self.sheety_header = { f"Authorization": f"Bearer {self.sheety_token}", } def get_data(self): return requests.get(url=self.sheety_api, headers=self.sheety_header).json() def update_sheet(self, object_id, column): response = requests.put(url=f"{self.sheety_api}/{object_id}", json=column, headers=self.sheety_header) response.raise_for_status()
主程序代码
from data_manager import DataManager from flight_search import FlightSearch from pprint import pprint import time sheet_class = DataManager() sheet_data = sheet_class.get_data() pprint(sheet_data) for index in range(len(sheet_data['data'])): flight_search = FlightSearch(sheet_data['data'][index]) iata_data = { "data": { "iataCode": "TESTING" } } sheet_class.update_sheet(object_id=sheet_data['data'][index]['id'], column=iata_data) time.sleep(2)
排查与解决步骤
- 检查Sheety权限配置:登录Sheety后台,确认你的API令牌是否开启了写入权限。GET请求仅需读取权限,而PUT请求需要编辑权限,可能你的令牌只配置了读权限。
- 验证请求URL正确性:确认PUT请求的URL格式是否符合Sheety要求,正确格式应为
https://api.sheety.co/[你的账户ID]/[表格名称]/[工作表名称]/[行ID],检查拼接后的URL是否存在路径错误,比如行ID是否正确传递。 - 核对请求体结构与列名:Sheety对列名大小写敏感,确认请求体中的
iataCode与Google Sheet中的列名完全一致,同时确保请求体的嵌套结构正确(外层为data包裹字段)。 - 调试请求细节:在
update_sheet方法中添加日志打印,确认请求头、URL、请求体是否正确:def update_sheet(self, object_id, column): print("请求头:", self.sheety_header) print("请求URL:", f"{self.sheety_api}/{object_id}") print("请求体:", column) response = requests.put(url=f"{self.sheety_api}/{object_id}", json=column, headers=self.sheety_header) print("响应状态码:", response.status_code) print("响应内容:", response.text) response.raise_for_status() - 用Postman做独立测试:绕过代码,用Postman手动发送PUT请求,使用相同的令牌、URL和请求体。如果Postman能成功,说明代码存在细节问题;如果Postman也失败,需重新检查Sheety的项目权限或令牌有效性。
内容的提问来源于stack exchange,提问作者Nadi
相关产品推荐
相关产品推荐

