Create a REST API With Lambda Non-Proxy Integration

Souvik Paul
Oct 22 · 7 min read
Image for post
Image for post
Photo by Burst on Unsplash

There are two methods to create an API with Lambda integration, viz. Lambda proxy integration and Lambda non-proxy integration.

In Lambda proxy integration, when the client makes a request, the API Gateway forwards the request to Lambda without transforming/modifying it. here, the request data is parsed by the Lambda function itself and the response is also handled by the lambda.

In Lambda non-proxy integration, when the client makes a request, the API Gateway is able to transform it and then forwards it to the lambda. Similarly, when the response data comes from the lambda function to the API Gateway, it sets the header, status code etc.

In this blog, we’ll create a REST API with Lambda non-proxy integration. But before that we need to understand few basic concepts like API, SOAP API, REST API, and Amazon API Gateway. For that, please visit the following link where I have explained everything in a simple way.

So, now we can start creating our API.

Prerequisites

  1. You should have an AWS account, and
  2. You should have the knowledge of Node.js.
  3. You should have downloaded curl, which is a command line tool and library for transferring data with URLs. Otherwise, if you have Postman installed in your system, then it will also work.

Procedure for downloading curl

Go to curl’s website and download the zip file in your system based on your OS and unzip it in your preferred drive. Open the unzipped folder and navigate to bin folder. Copy the absolute path to this folder and paste it in the Path variable as a new path under system variables section in the environment variables.

To check whether the curl is working properly or not, open the terminal and run curl --version, which will show the version of curl. If you are a windows user and want to check the version of curl in Powershell, then run curl.exe --version.

Step 1: Open the Lambda console and click on Create Function and select Author from Scratch. Enter the name of the function as LambdaNPfunc and select Node.js 12.x as the runtime. In Execution role, choose Create a new role from AWS policy templates. Enter Role name as MyRole and for Policy templates, choose Simple microservice permissions. Then hit Create Function. A new page will be opened, where the following code will be entered and deployed—

In the above code, 'use strict'; is declared at the beginning of a script which means it has global scope and all the codes in the script will be executed in strict mode. Strict mode makes it easier to write “secure” JavaScript where a variable without declaration is not allowed. In normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

The above handler function has three parameters —

(a) event — It is the data that is sent during the function call. The event object changes depending on what triggers the Lambda.

(b) context — It contains the methods available to interact with the runtime information.

(c) callback — It is used to return information to the one that invokes/triggers the Lambda. This parameter is not mandatory and not available in all cases.

Step 2: Now, we’ll test whether our function is working or not. Click on the Test button and then we’ll create new test template to pass information in the event object as an input to the function. Let’s give our Event name as testEvt. We’ll modify the event object that is in JSON format which is given below and will lick on Create button.

{
"name": "John",
"country": "India",
"level": "One",
"lang": "NodeJs"
}

Step 3: Now, we’ll again click on the Test button to run the code. After execution, the Execution result will be displayed, where we can see the results of console.log('Message: ', message); in the log output section. The result should be as follows -

Message: John, you have reached level one in NodeJs in India

So, that means our function is working properly.

Step 4: Now, we’ll create the API. Open the API console and under REST API section, click on Build. A new page will be opened. Under Create new API, choose New API. Then , under settings, enter MyAPI as the API name. We can leave the Description column. Endpoint Type should be Regional and then click Create API.

Now, in Resources, under Actions dropdown menu, select Create Resource. In the Resource name field enter country. In the resource path, enter {country}, which is an example of templated path variable used to take input from the client. Enable API Gateway Cors option should be checked. Then click Create Resource.

Again form the Actions dropdown menu, select Create Method and choose ANY. Click on the tick mark adjacent to ANY to save it. Now, for /{city} ANY method, in the Method execution section, select Lambda function for Integration type. Lambda proxy integration box should be unchecked. In the lambda function field, enter the name of the lambda function that we have created, i.e, LambdaNPfunc. Use default timeout box should be checked. Then, click on Save. Click OK in the Add Permission to Lambda Function popup to have API Gateway set up the required access permissions for the API to invoke the integrated Lambda function.

Step 5: Now, we’ll configure query string parameter, header parameter and payload property.

In the Method Execution section, choose Method Request. Expand the URL Query String Parameters section. Select Add query string. Enter level for
Name. Select the Required option and choose the check-mark icon to save the setting. Leave Caching unchecked to avoid an unnecessary charge.

Then, expand the HTTP Request Headers section. Click on Add header. Type lang for Name. Select the Required option and choose the check-mark icon to save the setting. Leave Caching unchecked to avoid an unnecessary charge.

Step 6: Now, we’ll define the Method request payload. Select Models in the API gateway primary navigation section and click on Create. Enter MyModel in Model Name field. For content-type, enter application/json. Model description can be left blank. In the Model Schema, enter the following —

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "InputModel",
"type": "object",
"properties": {
"callerName": { "type": "string" }
}
}

Now, click on Create Model to finish defining the input model.

Now, again from the primary navigation section, select Resources and click on the /{city} ANY method. Then select Method Request, and expand Request body. Select Add model and type application/json for Content type. Choose MyModel for Model name. Click the check-mark icon to save the setting.

Now, again click on /{city} ANY method and choose Integration Request to set up a body-mapping template. Expand the Mapping Templates section and click on Add mapping template and enter application/json for Content-Type. Click the check-mark icon to save the setting. In the popup that appears, click Yes, secure this integration. Then, select MyModel from Generate template to generate an initial mapping template. In the mapping template editor, enter the following and save it.

#set($inputRoot = $input.path('$'))
{
"country": "$input.params('country')",
"level": "$input.params('level')",
"lang": "$input.params('lang')",
"name": "$inputRoot.callerName"
}

Step 7: Now, we’ll test whether this API is working or not. Go to Method execution section and click on Test. In the Method dropdown menu. select POST. Enter India in path field, level=one in Query String field, lang:NodeJs in Headers field and {“callerName”:”John”} in the Request body field. Then, finally click on Test. The result should be give as below —

{"message": "John, you have reached level one in NodeJs in India"}

Step 8: Now, we’ll deploy our API. From the Actions dropdown menu, select Deploy API. Select [New stage] for Deployment stage and for Stage Name, enter test. Stage description and Deployment description can be left blank. Finally, click on Deploy. A new page will appear, where we can find the invoke URL, which should be copied and will look like —

https://beartt1mnid.execute-api.ap-south-1.amazonaws.com/test

Step 9: Now, we’ll open the terminal and type the following command -

curl -v -X POST \ 
'https://beartt1mnid.execute-api.ap-south-.amazonaws.com/test/India?level=one' \ -H 'content-type: application/json' \ -H 'lang: NodeJs' \ -H 'x-amz-docs-region: ap-south-1' \
-d '{ "callerName": "John" }'

Powershell users can run the following command —

curl.exe -v -X POST \ 
'https://beartt1mnid.execute-api.ap-south-.amazonaws.com/test/India?level=one' \ -H 'content-type: application/json' \ -H 'lang: NodeJs' \ -H 'x-amz-docs-region: ap-south-1' \
-d '{ "callerName": "John" }'

The output of above command will be -

{"message": "John, you have reached level one in NodeJs in India"}

Summary

In this article, we have gone through various topics like curl, APIs, SOAP and REST APIs, Amazon API Gateway, and API Gateway REST API with Lambda integration. Finally, we’ve created a REST API with Lambda non-proxy integration.

For this project, I took help from Amazon API Gateway documentation. Particularly, Build an API Gateway REST API with Lambda non-proxy integration.

References:

https://docs.aws.amazon.com/apigateway/index.html

AWS API Gateway documentation

https://docs.aws.amazon.com/lambda/index.html

Documentation on AWS Lambda

https://curl.haxx.se/

Website of curl

https://www.redhat.com/en/topics/api/what-are-application-programming-interfaces

Documentation on API

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store