簡體   English   中英

API POST-Request 適用於 PowerShell 但不適用於 Python

[英]API POST-Request works with PowerShell but not with Python

我有一個本地 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-example 只顯示 POST 通常有效

requests.postdata參數不接受字符串,您應該直接將 dict 傳遞給它:)

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

查看POST 請求快速入門

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM