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

使用Python调用DocuSign API创建模板时遇400错误求助

问题分析与解决建议

1. 环境变量调用错误

代码里payload中的documentBase64字段错误使用了getenv(document_base64)——document_base64已经是通过getenv("DOCUMENT_BASE64")获取到的变量值,再次调用getenv会把该变量值当作环境变量名去查找,必然无法获取正确的文件base64内容。

修复:
直接使用已获取的变量:

payload = {'documents':
               [{"documentBase64": document_base64,
                 "documentId": "1", "fileExtension": "pdf",
                 "name": "World_Wide_Corp_lorem"}], 'emailSubject': "Create template test"}

2. 缺少Content-Type请求头

当用json.dumps(payload)作为data参数时,必须手动添加Content-Type: application/json到请求头,否则DocuSign无法正确解析请求体。Postman会自动添加该请求头,这是Postman能成功但代码失败的核心原因之一。

修复方式二选一:

  • 手动添加请求头:
post_headers = {
    'Accept': 'application/json',
    'Authorization': token,
    'Content-Type': 'application/json'
}
  • 使用requests.post的json参数替代data=json.dumps(payload),requests会自动添加Content-Type头:
post_r = requests.post(
    url="https://demo.docusign.net/restapi/v2.1/accounts/b24dee2d-xxxx-xxxx-xxxx-d9d81de867ab/templates",
    headers=post_headers,
    json=payload
)

3. 重复传递account_id

URL路径中已经包含账户ID(/accounts/b24dee2d-xxxx-xxxx-xxxx-d9d81de867ab/),但代码又在params里重复传递account_id,导致URL查询参数中出现重复的账户ID,可能触发DocuSign的参数校验错误。

修复:
删除post_params变量,调用requests.post时去掉params=post_params参数。

完整修复后的代码

def create_template(token):
    docusign_account_id = getenv("DOCUSIGN_ACCOUNT_ID")
    document_base64 = getenv("DOCUMENT_BASE64")

    post_headers = {
        'Accept': 'application/json',
        'Authorization': token,
        'Content-Type': 'application/json'
    }

    payload = {
        'documents': [
            {
                "documentBase64": document_base64,
                "documentId": "1",
                "fileExtension": "pdf",
                "name": "World_Wide_Corp_lorem"
            }
        ],
        'emailSubject': "Create template test"
    }

    post_r = requests.post(
        url=f"https://demo.docusign.net/restapi/v2.1/accounts/{docusign_account_id}/templates",
        headers=post_headers,
        json=payload
    )

    # 建议先打印返回内容,便于排查后续问题
    print(post_r.text)
    post_r.raise_for_status()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:05:26