Create a Serverless REST API with Node.JS, AWS Lambda, DynamoDB & API Gateway

Written by mlabouardy | Published 2017/10/26
Tech Story Tags: aws | serverless | lambda | api-gateway | nodejs

TLDRvia the TL;DR App

In this post, I will show you how to build a RESTful API in Node.JSfollowing the Serverless approach using AWS Lambda, API Gateway & DynamoDB.

Serverless computing is a cloud computing execution model in which the cloud provider dynamically manages the allocation of machine resources

All the code is available on my Github

1 — API Specification

The REST API service will expose endpoints to manage a store of movies. The operations that our endpoints will allow are:

2 — DynamoDB Table

Go to DynamoDB Console, then click on “Create table” button, and fill the table name and set a primary key:

3 — Write a new Movie Lambda Function

The code is self explanatory, I have used the put method to insert a new movie item and uuid library to generate a random unique id for the movie item:

Go to the Lambda Dashboard and create a new function as below:

Add the DynamoDB table name as an environment variable and update the handler name to the function name in the code above:

Note: you should use a IAM Role with permission to access DynamoDB& Lambda.

Once created, you can click on “Test” and send a JSON as below:

The item has been successfuly inserted into DynamoDB:

4 — List all Movies Lambda Function

The code is self explanatory, I used scan method to fetch all items from the table:

Fill the function configuration as below:

Similar to the write function, we need to add DynamoDB table name as an environment variable:

Once created, you could test the function by clicking on the “Test” button:

Congratulation !

We have successfuly created our Lambda functions:

5 — Setup API Gateway

Go to API Gateway Console and create a new API.

5.1 — GET /movies

5.2 — POST /movies

Once done, deploy the API:

Copy down the API Invoke URL:

6 — Test

Let’s test it out:

6.1 — Create a Movie

With Postman:

With cURL:

|curl -sSX POST -d ‘{“name”:”Gladiator”}’ https://3z0neyn1nf.execute-api.us-east-1.amazonaws.com/prod/movies

6.2 — List Movies

With Postman:

With cURL:

|curl -sSX GET https://3z0neyn1nf.execute-api.us-east 1.amazonaws.com/prod/movies

If we check our DynamoDB Table


Published by HackerNoon on 2017/10/26