简体   繁体   中英

API POST-Request works with PowerShell but not with Python

I got a local API that I want to test with very basic POST-requests. The PowerShell test-script works perfectly fine but the Python test-script (that should work the same way) does not.


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))

The returned error of the API is not meaningful since the API is still in the early testphase

PS: I didn't tag PowerShell here since the PowerShell-example only shows that the POST generally works

requests.post 's data argument doesn't take a string, you should pass it the dict directly :)

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

See the quickstart from requests on POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM