< YALU STUDIO >

Building Serverless REST API with Node.js, AWS Lambda, API Gateway, DynamoDB,...

Word count: 315 / Reading time: 2 min
2019/10/10 Share
  1. Install the serverless framework

    1
    npm install -g serverless
  1. Configure AWS IAM keys

    Replace [Access key ID] and [Secret access key] with your IAM credentials. If you don’t have it, create one in the AWS console, My Security Credentials.

    1
    serverless config credentials --provider aws --key [Access key ID] --secret [Secret access key]
  2. Generate a boilerplate

    1
    serverless create --template aws-nodejs --path [folder]

    Then it will create a boilerplate using the template for Node.js. Go into the root folder, and install the required packages.

    1
    2
    cd [folder]
    npm init -y && npm install

    And also install express and serverless-http with the command below:

    1
    npm install express serverless-http
  1. Expose an HTTP endpoint

In the serverless.yml file, comment out and change the following code:

1
2
3
4
5
6
7
8
functions:
app:
handler: app.server
events:
- http:
path: /
method: get
cors: true
  1. Set up Express

    Delete handler.js file, and create one named app.js:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const express = require('express');
    const app = express();
    const sls = require('serverless-http');

    app.get('/', async (req, res, next) => {
    res.status(200).send('Hello Serverless!')
    });

    module.exports.server = sls(app);

    Noticed that, AWS Lambda does not support the ES6 import specifier (at the time of 10/10/2019). import express from 'express' will cause an internal server error. And in the log we can see that it says "Runtime.UserCodeSyntaxError: SyntaxError: Unexpected identifier"

  1. Deploy
1
serverless deploy
  1. Test the API

    In the output, we can see that it exposes an endpoint probably like this.

    1
    2
    endpoints:
    GET - https://xxxx.execute-api.xx-xxxx-x.amazonaws.com/xxx/

    Let’s try it with the command below:

    1
    curl https://xxxx.execute-api.xx-xxxx-x.amazonaws.com/xxx/

    And we will get our message back, “It’s working”.

CATALOG