Building a stateless serverless web application backend

Here, we are going to build the stateless web application backend, and later on we will add the database. This application will allow users to create, read, update, and delete blog articles. Then we will deploy and test our little blog API.

Open the Atom text editor in the empty blog-app directory. Let's use the command line to create some files:

sls create -t aws-nodejs -n blog

I have used sls create to create a new service, but with a new name—blog.

This command line will generate two files, serverless.yml and handler.js, as shown in the following screenshot:

Open the serverless.yml file and delete some of the comments. Once that is done, the next thing you must do is change the region. Here, I am deploying my service in the Frankfurt region in eu-central-1, as follows:

service: blog
provider:
name: aws
runtime: nodejs4.3
stage: dev
region: eu-central-1

Now, scroll down to the function. You have to change the name of the Lambda function from hello to something like createArticle. Once that is done, we need to rename the module that gets exported to the handler.js file, as follows:

functions:
createArticle:
handler: handler.createArticle

Since the module that the Lambda function references as a handler function has been renamed, you also need to rename it in the handler.js file. So replace hello with createArticle, as shown in the following screenshot:

'use strict';
module.exports.createArticle = (event, context, callback) =>
const response = {
statusCode: 200,
body: JSON.stringify({

message: 'Go Serverless v1.0! Your function executed successfully!',
input: event,
}),
};

Once that is done, let's go back to the serverless.yml file and add our API Gateway:

functions:
createArticle:
handler: handler.createArticle
events:
- http:
path: users/create
method: get

So the things that must be changed are the path and the method. For consistency, let's name the path createArticle, while the method should be named the post method rather than the get method:

functions:
createArticle:
handler: handler.createArticle
events:
- http:
path: createArticle
method: post

Now let's deploy our service by typing sls deploy:

sls deploy

The following screenshot shows the deployed service:

Once it is deployed, invoke the Lambda function and see if it works:

Next, let's use Postman to check whether the API also works. For that purpose, we will need the endpoint that is provided in the preceding code. Copy the link and open Postman.

In Postman, enter the request URL. Since a post method has been deployed, switch the tab to Post and click Send:

Now, you can change the file structure by going back to the editor and changing it.

Let's do that!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.227.231