API POST-Request适用于PowerShell,但不适用于Python

时间:2019-03-12 14:25:27

标签: python json python-requests

我有一个本地API,要通过非常基本的POST请求进行测试。 PowerShell测试脚本可以很好地工作,但是Python测试脚本(应该以相同的方式工作)却不能。


PowerShell:api_post.ps1

$url = "http://test.local/"

$headers = @{"Content-Type" = "application/json"}

$payload = @(
    @{
        "Order_Number" = "123-vfs"
        "SKU"          = 123
        "Company"      = "Test Ltd"
    }
)

$payload = ConvertTo-Json -InputObject $payload

# Works exactly as it should
Invoke-RestMethod -Uri $url -Method "POST" -Headers $headers -Body $payload

Python api_post.py

import json
import requests

URL = "http://test.local/"

HEADERS = {
    "Content-Type": "application/json"
}

PAYLOAD = [
    {
        "Order_Number": "123-vfs",
        "SKU": 123,
        "Company": "Test Ltd",
    }
]

# Returns an error
requests.post(URL, headers=HEADERS, data=json.dumps(PAYLOAD))

API返回的错误没有意义,因为API仍处于早期测试阶段

PS:我没有在此处标记PowerShell,因为PowerShell示例仅显示POST通常有效

1 个答案:

答案 0 :(得分:1)

requests.post的{​​{1}}参数不带字符串,您应该直接将字典传递给它:)

data

请参见quickstart from requests on POST