HyperDevil
HyperDevil

Reputation: 2649

API Gateway - Lambda Proxy - Python Internal server error

I have issues parsing the input data from event in Python 3.7.

def lambda_handler(event, context):
 image = event['image']
 siteid = int(event['siteid'])
 camid = int(event['camid'])

Error:

Lambda execution failed with status 200 due to customer function error: 'image'.

Method request model:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "UploadModel",
  "type": "object",
  "properties": {
    "image": { "type": "string" },
    "siteid": { "type": "string" },
    "camid": { "type": "string" }
    }
}

Use Lambda Proxy integration: ON

It works fine directly from the lambda console with a simple input array:

{
    "image": "xxxx"
    "siteid": 2,
    "camid": 1
}

Response function:

def response(message, status_code):
    return {
        "statusCode": str(status_code),
        "body": json.dumps(message),
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": '*'
            },
        }

Upvotes: 3

Views: 2753

Answers (1)

Noel Llevares
Noel Llevares

Reputation: 16087

You are assuming the wrong shape for the event object.

When you use Lambda Proxy Integration, the event takes the following shape...

{
    "resource": "Resource path",
    "path": "Path parameter",
    "httpMethod": "Incoming request's method name"
    "headers": {String containing incoming request headers}
    "multiValueHeaders": {List of strings containing incoming request headers}
    "queryStringParameters": {query string parameters }
    "multiValueQueryStringParameters": {List of query string parameters}
    "pathParameters":  {path parameters}
    "stageVariables": {Applicable stage variables}
    "requestContext": {Request context, including authorizer-returned key-value pairs}
    "body": "A JSON string of the request payload."
    "isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
}

Reference: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

Your request model is only applicable to the body of event.

To illustrate this, try using this handler that returns the event back as a response:

def lambda_handler(event, context):
    return {
        "statusCode": str(status_code),
        "body": json.dumps(message),
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": '*'
            },
        }

Upvotes: 4

Related Questions