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

如何调用Swagger生成的API Client方法并传递Header/Body等参数?

正确传递Swagger Codegen 3.0生成API的各类参数

1. Body参数

直接按方法定义的body参数传递即可,这是生成方法的显式参数,示例:

your_body = {"key": "value"}
response, status, headers = dummy_key_api.post_dummy_key_with_http_info(body=your_body)

2. 路径参数(Path Params)

这类参数会被生成方法直接设为必填参数,比如接口路径是/dummy/{key_id},调用时直接传key_id就行:

response, status, headers = dummy_key_api.get_dummy_key_with_http_info(key_id=12345)

方法内部会自动把参数填充到URL路径中,不用手动构造path_params。

3. 查询参数(Query Params)

如果接口定义了查询参数,生成的方法会将它们作为可选(或必填)参数提供,直接传入即可:

# 比如接口支持page和size分页参数
response, status, headers = dummy_key_api.list_dummy_keys_with_http_info(page=2, size=20)

要是需要传递Swagger定义中未声明的额外查询参数,用query_params关键字传递字典:

extra_query = {"custom_param": "test"}
response, status, headers = dummy_key_api.list_dummy_keys_with_http_info(page=2, query_params=extra_query)

4. 请求头参数(Header Params)

全局头部(所有请求生效)

如果所有API请求都需要添加固定头部,直接操作API类的api_client属性:

api_client = dummy_key_api.api_client
# 添加自定义头部
api_client.default_headers["X-Auth-Token"] = "your_token"
api_client.default_headers["Content-Type"] = "application/json"

之后这个api_client发起的所有请求都会带上这些头部。

单次请求头部(仅当前请求生效)

生成的方法可能未将headers设为显式参数,但底层的call_api方法支持header_params,你可以通过关键字参数传递:

custom_headers = {"X-Custom-Header": "custom_value", "Accept": "application/xml"}
response, status, headers = dummy_key_api.post_dummy_key_with_http_info(
    body=your_body,
    header_params=custom_headers
)

如果生成的方法没有预留**kwargs,可以临时修改api_client的default_headers,请求完成后再恢复:

# 先保存原头部
original_headers = dummy_key_api.api_client.default_headers.copy()
# 添加临时头部
dummy_key_api.api_client.default_headers.update(custom_headers)
# 发起请求
response, status, headers = dummy_key_api.post_dummy_key_with_http_info(body=your_body)
# 恢复原头部
dummy_key_api.api_client.default_headers = original_headers

5. 额外请求控制

如果需要更精细地控制请求(比如超时、认证),直接修改api_client的属性即可,示例:

# 设置请求超时为30秒
dummy_key_api.api_client.timeout = 30

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:55:23