You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Python的httpx API请求失败?Postman可正常执行

问题原因及解决办法

核心问题

你的代码存在三个关键错误,导致API返回缺少id参数的报错:

1. 请求参数传递位置错误

Postman中你是将参数放在**请求体(Body)**里,但Python代码里用了params=params,这会把参数拼接到URL的查询字符串中,而非作为JSON请求体发送。API无法从查询参数里获取所需的id字段,因此报错。

2. 引用错误的headers变量

代码里定义了headers字典,但请求时写的是headers=api.headers,这会导致请求没有带上正确的授权和内容类型头,API无法正确解析请求体。

3. 变量赋值语法错误

company_id = {company_id}和record_id = {record_id}是无效的Python语法,需替换为实际的ID值,比如company_id = "12345"。

修正后的代码

import httpx
import ujson

# 替换为实际的密钥和ID值
bearer_key = "你的bearer密钥"
user_key = "你的user密钥"
staff_id = "员工ID"
service_id = "服务ID"
company_id = "公司ID"
record_id = "记录ID"

headers = {
    'Accept': 'application/vnd.yclients.v2+json',
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {bearer_key}, User {user_key}'
}

# 请求体数据
payload = {
    "staff_id": staff_id,
    "services": [{"id": service_id}],
    "client": {"name": "client_name", "phone": "**********111"},
    "datetime": "2023-07-04T09:00:00+03:00",
    "seance_length": 600
}

url = f'https://api_url.com/api/{company_id}/{record_id}'
session = httpx.Client()
# 使用json参数传递请求体,headers用定义好的变量
response = session.put(url, headers=headers, json=payload)
first_request = ujson.loads(response.text)
print(first_request)

关键修正点

  • 将params=params改为json=payload,让httpx自动将数据序列化为JSON请求体发送
  • 把headers=api.headers修正为headers=headers,确保请求带上正确的头信息
  • 修正company_id和record_id的赋值语法,填入实际的ID值

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 17:48:21