Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access the request json_body when using Chalice

I'm attempting to make a curl request to my python api that is using the AWS package Chalice.

When I try to access the app.current_request.json_body a JSON Parse error is thrown. Cannot figure out why this is happening. My JSON is formatted properly as far as I can tell.

Here is the curl request:

(echo -n '{"data": "test"}') |
curl -H "Content-Type: application/json"  -d @-  $URL

Here is the python Chalice code:

app = Chalice(app_name='predictor')

@app.route('/', methods=['POST'], content_types=['application/json'])
def index():
    try:
        body = app.current_request.json_body
    except Exception as e:
        return  {'error':  str(e)}

When I invoke the route using the above curl request I get the following error:

{"error": "BadRequestError: Error Parsing JSON"}

Note: When I remove the .json_body from the app.current_request. I no longer get the error.

Any thoughts?

like image 931
Nicholas Porter Avatar asked Nov 01 '25 13:11

Nicholas Porter


1 Answers

The documentation indeed indicates that the problem is Content-Type:

The default behavior of a view function supports a request body of application/json. When a request is made with a Content-Type of application/json, the app.current_request.json_body attribute is automatically set for you. This value is the parsed JSON body.

You can also configure a view function to support other content types. You can do this by specifying the content_types parameter value to your app.route function. This parameter is a list of acceptable content types.

It suggests that changing the Content-Type might make json_body work, but I didn't manage to have any success with it.

However using app.current_request.raw_body.decode() instead of app.current_request.json_body solves the problem.

like image 86
BanzaiTokyo Avatar answered Nov 04 '25 03:11

BanzaiTokyo