首页 > 解决方案 > API POST-Request 适用于 PowerShell 但不适用于 Python

问题描述

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


电源外壳: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

Pythonapi_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 通常有效

标签: pythonjsonpython-requests

解决方案


requests.postdata参数不带字符串,您应该直接将其传递给 dict :)

requests.post(URL, headers=HEADERS, data=PAYLOAD[0])

请参阅POST 请求中的快速入门


推荐阅读