python - 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 通常有效
解决方案
requests.post
的data
参数不带字符串,您应该直接将其传递给 dict :)
requests.post(URL, headers=HEADERS, data=PAYLOAD[0])
推荐阅读
- angular - 如何在登录后显示选项卡并更改选项卡而不在 Ionic 的另一个页面上创建 root?
- eclipse - 在 Eclipse 中更改团队-> 远程-> 上游 URI
- python - 如何检查 urllib.urlretrieve 是否能够使用 python 到达主机?
- python - 通过 Embed 使用 Discord.py 显示来自 JSON 的排行榜统计信息
- powershell - 用于打开数据库文件并将其数据导出到 Excel 文件的 Powershell 脚本或计划任务
- webassembly - Webassembly 缺少 _free 函数无法释放内存
- html - 在引导程序中的导航栏内对齐内容
- localization - 在 Django 模板中包含非本地化值的好方法
- c# - webApi 的路由属性中的通配符
- haskell - 在 Haskell 函数之外使用 where