AWS Lamda, API Gateway, Node - How to easily get access to query parameters in GET, POST, PUT.. requests.
Khoj Badami
Posted on May 8, 2021
Video Version Of Post
below is the text version of the post.
The Problem - Long and complex "event" object is given by API Gateway.
When you create a new Lamda function, the default code is as follows:
exports.handler = async (event) => {
// AWS gives you this "event" as a parameter.
};
The "event" parameter is supposed to have all the details about the HTTP request. But, the "event" object is long and has a lot of stuff you don't care about.
Below is a sample event object for a GET request (with HTTP API version 2):
{
"version": "2.0",
"routeKey": "ANY /http_api_post_test",
"rawPath": "/default/http_api_post_test",
"rawQueryString": "first_name=Khoj",
"headers": {
"accept": "*/*",
"accept-encoding": "gzip, deflate, br",
"cache-control": "no-cache",
"content-length": "0",
"host": "he4vxo0r3j.execute-api.ap-south-1.amazonaws.com",
"postman-token": "9d390677-0e57-4060-9040-850e94a5c964",
"user-agent": "PostmanRuntime/7.26.8",
"x-amzn-trace-id": "Root=1-608cd65c-3c8c34f603f20b100a7449d4",
"x-forwarded-for": "106.220.136.5",
"x-forwarded-port": "443",
"x-forwarded-proto": "https"
},
"queryStringParameters": {
"first_name": "Khoj"
},
"requestContext": {
"accountId": "941626753563",
"apiId": "he4vxo0r3j",
"domainName": "he4vxo0r3j.execute-api.ap-south-1.amazonaws.com",
"domainPrefix": "he4vxo0r3j",
"http": {
"method": "GET",
"path": "/default/http_api_post_test",
"protocol": "HTTP/1.1",
"sourceIp": "106.220.136.5",
"userAgent": "PostmanRuntime/7.26.8"
},
"requestId": "eoZuigwtBcwEPKg=",
"routeKey": "ANY /http_api_post_test",
"stage": "default",
"time": "01/May/2021:04:17:32 +0000",
"timeEpoch": 1619842652981
},
"isBase64Encoded": false
}
The Solution - There is an NPM Package For That (I made it)
Here is a link: https://www.npmjs.com/package/lamda-api-gateway-event-parser
This package helps you easily and uniformly extract the parameters from the event object.
The package, handles the following types of HTTP events/requests:
- Simple GET Request with Query String Params
- POST, PUT, PATCH, DELETE request with application/x-www-form-urlencoded form data.
- POST, PUT, PATCH, DELETE request with multipart/form-data form data.
- JSON Body of HTTP Request
- XML Body of HTTP Request
What you get as an output...
In all the above cases, you get as an output an object with 3 to 5 keys with the below shape:
{
userAgent: 'The user agent of the caller (in-case you need that)',
originalEvent: {}, // the whole original event object, just in-case.
prams: {}, // A nice neat prams object irrespective of the type of input HTTP event.
error: 'In case there is an error parsing the XML or JSON, you get an error here.',
[xmlString / jsonString]: 'The original XML / JSON string in-case you need that and are not happy with the parsing.'
}
Quick Start
How to install?
The usual:
nmp i lamda-api-gateway-event-parser
yarn add lamda-api-gateway-event-parser
How to use?
Usually, parsing the event will be the very first thing you do in your Lamda Function. So, just add it like so..
const eventParser = require('lamda-api-gateway-event-parser'); // Bring it in.
exports.handler = async (event) => {
let niceNeatParsedEvent = eventParser.parse(event); // Parsing the event.
// All the other awesome things you need to do
};
About File Uploads & multipart/form-data Events
If the event we get is of the type: multipart/form-data, the package will extract all the form fields as usual and make a nice neat "params" object as described above.
In the case of the file, the contents of the file will be saved into the "tmp" folder (which is provided by AWS Lamda). When the "params" object is looked at, it will look like the following:
params: {
simple_param_1: "Simple text value",
file_upload_param_name: {
type: 'file',
filename: 'the name of the file',
contentType: 'content type eg: image/jpeg',
path: 'file path in lamda environment. eg: "/tmp/cat.jpeg"'
}
}
Major credits to: https://github.com/myshenin/aws-lambda-multipart-parser for this part. But the repo is a little outdated and no longer maintained.
Not working as expected?
There are 2 assumptions this package makes (if your Lambda function is not running as per these assumptions, it may not work):
- On the API Gateway side, we are using HTTP API (not REST API). Why? Because it's FASTER & CHEAPER. More info here.
- API Gateway version 2 (latest). This version has a different "event" object structure from version 1. Because of this, the package might not be able to identify the "event type" and deploy the correct parser. This is the default from AWS for new functions right now.
Posted on May 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.