Serverless tutorial on creating Rest API with API Gateway and AWS Lambda function

  1. Creating AWS lambda function
  2. Adding API gateway event to Lambda function
  3. Creating POST REST API using API Gateway with Lambda integration

Writing an lambda function using serverless

Your basic serverless template contains two file serverless.yml that contains the basic orchestration of projects like permissions, project information, lambda function information and events and handler.js which is your main function or code that serves as a lambda function.

  • So first create a file add.js
  • add.js takes two parameter param1 and param2 as POST request. Add these parameters and give the result of addition in response.
  • If any error occurs it returns an error.
'use strict';exports.handler = async (event) => {
try{
let param = JSON.parse(event.body);
let result = param.param1 + param.param2;
console.log("result",result);
return{
StatusCode: 200,
body:JSON.stringify({
result: result
})
}
}catch(err){
console.log("Error",err);
return{
StatusCode: err.statusCode? err.statusCode :500,
body:JSON.stringify({
error: err.name ? err.name: "Exception",
message: err.message ? err.message : "Unknown error"
})
}
}};

Deploying lambda function

  • To deploy the function in AWS type serverless deploy -s prod where prod is the stage name
  • To test this we will use Postman. Copy the API endpoint and paste in Postman. Choose POST request. write a body in json
{"param1" : 1, "param2": 3}

--

--

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
vaibhav sharma

vaibhav sharma

5 Followers

Full Stack IoT developer working on effective Wireless Sensor Network