简体   繁体   English

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

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

I wanted to confirm/see if there is a better way to be making a post request to an API endpoint that was generated for an AWS Lambda?我想确认/查看是否有更好的方法向为 AWS Lambda 生成的 API 端点发出发布请求? Simply I'm trying to optimize this curl without using a subprocess call.只是我试图在不使用子进程调用的情况下优化此卷曲。 With this code I get an error status code of 400.使用此代码,我得到 400 的错误状态代码。

Code I'm trying to optimize我正在尝试优化的代码

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

Python script I've created:我创建的 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())

Error Message错误信息

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

The JSON needs to be loaded properly before the post request. 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())

This gives a status code of 200 & the proper JSON response.这给出了 200 的状态代码和正确的 JSON 响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 python 中使用 AWS Lambda 向外部 API 发送 Post 请求 - Send Post request to an external API using AWS Lambda in python 如何使用 Python 和 MySQL 向 AWS Lambda 发送 POST 请求 - How to send a POST request to AWS Lambda using Python and MySQL 无法使用python请求模块在AWS lambda中进行API post调用 - Trouble using python request module to make API post call within AWS lambda 如何在使用来自 AWS Lambda 的 307 重定向(POST 方法和正文)在 python 中传递请求正文 - How to do pass a Request Body while doing a 307 Redirect with a( POST Method and body ) from AWS Lambda , in python 如何使用AWS Web API和Lambda验证无服务器Web请求? - How to authenticate serverless web request using AWS Web API and Lambda? 我如何在 python 中为 auth.gg api 正确 request.post() - How do I request.post() properly in python for auth.gg api JSON 有效负载,AWS Lambda(Python),API 网关 - JSON Payload, AWS Lambda (Python), API Gateway AWS Lambda Python 3 处理 POST 文件 - AWS Lambda Python 3 handle POST file 如何从AWS API将变量传递给Python Lambda - How do I pass variables to Python Lambda from AWS API 如何获取在 s3 中上传的最新 object 名称并使用 AWS Lambda 将该数据(json)推送到不同的 api(点击 api)? - How do I get the latest object name uploaded in s3 and push that data(json) to a different api (hit an api) using AWS Lambda?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM