2

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? Simply I'm trying to optimize this curl without using a subprocess call. With this code I get an error status code of 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:

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)
kevin_theinfinityfund
  • 1,631
  • 17
  • 18

1 Answers1

0

The JSON needs to be loaded properly before the post request.

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.

kevin_theinfinityfund
  • 1,631
  • 17
  • 18