Serverless is now one of the latest trends in technology for startups, might also be one way to learn on how to create a REST API in a very quick way. What we will cover are the steps to start creating a serverless function focusing on local dev environment.
The following needs to be installed as a prerequisite:
We will be using VsCode as our IDE, right after the installation of our prerequisites, we’ll verify each of them:
At this point, we’re all set in developing our first function in serverless, NodeJs will be our language of choice in developing our first API.
First, we will be creating our folder and name it user, inside our folder we will be creating our first serverless function using the following command:
serverless create — template aws-nodejs
Other commands can be found here but we’ll just cover the basics.
There would be 2 files generated inside our folder, the handler.js and serverless.yml, our handler.js is the entry point for our lambda function, while the serverless.yml would be the metadata of our service which also includes the infrastructure resources.
Basically this would require us to deploy our application in AWS, but, that would not be the case in this tutorial. We will be using the serverless offline plugin in order for us to test our application without deploying it to AWS, the following command would be the installation of the plugin:
npm install serverless-offline — save-dev
This will install the dependency we need in our application and add it is as well in our serverless.yml in the plugin section:
serverless offline
After adding our plugin, we will execute the command above to make our serverless application run locally in offline:
In the above image, it provides the details of our serverless application, for us to invoke the function, we would be doing some modifications in our serverless.yml.
We are going to expose our function as an http endpoint, we will be adding an event to our serverless.yml:
In the events, we are going to declare our function as an http endpoint with a path hello and our method would be GET, as we set all the necessary fields we will run the same command using the offline plugin:
This time it will display the list of APIs available on our serverless application. To test our application, we can use postman, curl or even our browser.
At this point we were able to create at least a basic endpoint in serverless.