Sefton de Pledge
Sefton de Pledge

Reputation: 19

AWS Lambda Chalice app not receiving request payload

I have a small lambda function that I am creating with AWS Chalice in Python. When testing locally all works as intended and my test request works perfectly. However when running chalice deploy and then testing the same request to the hosted API I get the following error.

Traceback (most recent call last):
File "/var/task/chalice/app.py", line 1913, in _get_view_function_response
File "/var/task/app.py", line 34, in questions
payload = parse_qs(body)['data'][0]
KeyError: 'data'

app.py is as follows

# other imports
from urllib import parse_qs

def encode_payload(payload):
    '''encodes generic payload'''
    return base64.b64encode(pickle.dumps(payload)).decode('utf-8')

def decode_payload(payload):
    '''decodes generic payload'''
    return pickle.loads(base64.b64decode(payload))

app = Chalice(app_name='markthis-api')

@app.route('/questions', methods=['GET'], content_types=['application/json'])
def questions():
    style = app.current_request.query_params['style']
    body = app.current_request.raw_body.decode()

    payload = parse_qs(body)['data'][0]
    img = decode_payload(payload)

    stuff = find_questions(img, style)

    return {'pickle': encode_payload(stuff)}

test.py

def api_request(img, style):
    url = f'https://api-code-etc.execute-api.eu-west-2.amazonaws.com/api/questions?style={style}'
    #url = f'http://localhost:8000/questions?style={style}'

    headers = {'Content-Type': 'application/json'}
    payload = {'data': encode_payload(img)}

    return requests.get(url, data=payload, headers=headers)

I am new to AWS and Chalice and have no idea what is causing this issue. The API has one other endoint '/' which returns {'hello': 'world'}. This works fine when deployed.

Any help much appreciated

Upvotes: 0

Views: 458

Answers (1)

Fatih Ersoy
Fatih Ersoy

Reputation: 739

When Content-Type is "application-json" the preferred method is using .json_body. Instead of;

body = app.current_request.raw_body.decode()

Doing this might resolve the problem:

body = app.current_request.json_body

Upvotes: 1

Related Questions