如何使用 Python 使用 JSON 文件正确执行 AWS Lambda API Post 请求

How to properly do an AWS Lambda API Post Request with JSON file using Python

我想 confirm/see 是否有更好的方法向为 AWS Lambda 生成的 API 端点发出 post 请求?只是我试图在不使用子进程调用的情况下优化此卷曲。使用此代码,我得到错误状态代码 400。

我正在尝试优化的代码

$ curl -X POST -d @test.json -H "x-api-key: {API_KEY}" {URL}

Python 我创建的脚本:

import requests

URL = "some_url"
API_KEY = "some_api_key"

headers = {'x-api-key': API_KEY}
r = requests.post(URL, headers=headers, json=test.json)
print(r.status_code)
print(r.json())

错误信息

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

需要在 post 请求之前正确加载 JSON。

import requests
import json

URL = "some_url"
API_KEY = "some_api_key"
headers = {'x-api-key': API_KEY}

with open("test.json") as f:
    data = json.load(f)

r = requests.post(URL, headers=headers, json=data)
print(r.status_code)
print(r.json())

这给出了状态代码 200 和正确的 JSON 响应。