Request body serialization differences when lambda function invoked via API Gateway v Lambda Console

2024/9/30 11:28:44

I have a simple API set up in AWS API Gateway. It is set to invoke a Python 2.7 lambda function via API Gateway Proxy integration.

I hit a strange error in that the lambda worked (processed the body correctly and updated a DB) when invoked locally and through the lambda test console, but not through curl or Postman.

Turns out that, when invoked through the lambda test console, the event['body'] object is coming through as a dict. When called via an HTTP client, it's coming through as a string (Unicode).

I can work around it of course, but I'd like to understand it, and I'd also prefer a proper Python object. I'd also like to be able to use the lambda test console, but currently I can't as it passes its input differently.

Is there a configuration switch I'm missing which will force API Gateway to serialize the request body (as well as all other params) as a python dict or proper object? The documentation on the specifics of what is passed is sparse, stating:

event – AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type.

I get that this blurb covers what I'm seeing, but it's not exactly helpful.

Answer

When you invoke the lambda locally or through the Lambda console, you are invoking that lambda directly and so your lambda receives exactly what you're sending.

When you invoke it through API Gateway, API Gateway creates the event object for you based on your HTTP request. It adds the HTTP headers, path, query strings, payload, etc.

Here's a summary of what you're getting as an event from an API Gateway invocation:

{"resource": "Resource path","path": "Path parameter","httpMethod": "Incoming request's method name""headers": {Incoming request headers}"queryStringParameters": {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: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format

As you can see, the body will be sent to you as a string which you can parse using json.loads().

https://en.xdnf.cn/q/71086.html

Related Q&A

Determining a homogeneous affine transformation matrix from six points in 3D using Python

I am given the locations of three points:p1 = [1.0, 1.0, 1.0] p2 = [1.0, 2.0, 1.0] p3 = [1.0, 1.0, 2.0]and their transformed counterparts:p1_prime = [2.414213562373094, 5.732050807568877, 0.7320508075…

Split datetime64 column into a date and time column in pandas dataframe

If I have a dataframe with the first column being a datetime64 column. How do I split this column into 2 new columns, a date column and a time column. Here is my data and code so far:DateTime,Actual,Co…

Django - Setting date as date input value

Im trying to set a date as the value of a date input in a form. But, as your may have guessed, its not working.Heres what I have in my template:<div class="form-group"><label for=&qu…

ReduceLROnPlateau gives error with ADAM optimizer

Is it because adam optimizer changes the learning rate by itself. I get an error saying Attempting to use uninitialized value Adam_1/lr I guess there is no point in using ReduceLRonPlateau as Adam wil…

How to make add replies to comments in Django?

Im making my own blog with Django and I already made a Comments system.. I want to add the replies for each comment (like a normal comments box) and I dont know what to do this is my current models.py …

Which Regular Expression flavour is used in Python?

I want to know which RegEx-flavour is used for Python? Is it PCRE, Perl compatible or is it ICU or something else?

Python regex: Including whitespace inside character range

I have a regular expression that matches alphabets, numbers, _ and - (with a minimum and maximum length).^[a-zA-Z0-9_-]{3,100}$I want to include whitespace in that set of characters.According to the Py…

Python - how can I override the functionality of a class before its imported by a different module?

I have a class thats being imported in module_x for instantiation, but first I want to override one of the classs methods to include a specific feature dynamically (inside some middleware that runs bef…

Calling a stateful LSTM as a functional model?

I have a stateful LSTM defined as a Sequential model:model = Sequential() model.add(LSTM(..., stateful=True)) ...Later, I use it as a Functional model:input_1, input_2 = Input(...), Input(...) output_1…

How to cluster Gantt bars without overlap?

Using create_gantt I have overlapping start and end dates: import plotly.plotly as py import plotly.figure_factory as ff import plotlydf = [dict(Task="Milestone A", Start=2017-01-01, Finish=2…