Building a REST API with NodeJS,Express and DynamoDB

Author: Praweg Koirala

🗓️ March 23, 2023

⌛️ 1 mins

🌱 Seedling

🏷️    backend | nodeJS | intermediate

***************** This is a mock blog (real content coming soon…😉) ***************

this simple example builds REST API with following schema database of users

id:String, email: String ,gender:String, Name: String

The dependencies used in this project are as follows:

"dependencies": { "aws-sdk": "^2.1341.0", "dotenv": "^16.0.3", "express": "^4.18.2", "nodemon": "^2.0.22" }

We will create a .env file and store all the Credential needed to connect and communicate with the AWS-DynamoDB. it should look as such

AWS_ACCESS_KEY_ID=BHFAWHJBJHVSES AWS_SECRET_ACCESS_KEY=MNGk9KBjjhkjDGHVbjbhjDFGCFDS AWS_DEFAULT_REGION=us-west-1

We will set up the configuration for DynamoDB in the file DynamoDB.js

Then we will create the CRUD function to create , read, update and delete user info from dynamodb.

Below is the code for dynamodb.js

import AWS from 'aws-sdk'; import dotenv from 'dotenv'; // here we are loading the environment variables from the .env file dotenv.config(); // here we are destructuring the AWS object to get the config and DynamoDB object const{config, DynamoDB} = AWS; // here we are configuring the AWS environment AWS.config.update({ region: process.env.AWS_DEFAULT_REGION, accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, maxRetries:10, retryDelayOptions: {base: 200} }) // here we are creating a new instance of the DynamoDB client export const dynamoClient = new DynamoDB.DocumentClient(); // this is the name of the table we created in DynamoDB const TABLE_NAME = "users"; // this is the function that will get all the users from the table, it will return a promise export const getUsers = async ()=>{ const params = { TableName:TABLE_NAME }; return await dynamoClient.scan(params).promise(); } // this is the function that will get a user by id(individual entry), it will return a promise export const getUserByID = async (id)=>{ const params = { TableName: TABLE_NAME, Key:{ id } } return await dynamoClient.get(params).promise(); } // this is the function that will add or update a user(if the entry already exist with the same id will update), it will return a promise export const AddorUpdateUser = async (user)=>{ const params ={ TableName: TABLE_NAME, Item: user } return await dynamoClient.put(params).promise(); } // this is the function that will delete a user by id, it will return a promise export const deleteUser = async(id)=>{ const params ={ TableName: TABLE_NAME, Key:{ id } } return await dynamoClient.delete(params).promise(); }

All the routing for different operations , getAllUsers, GetUserById, EditUser & Delete User will be setup in a separate file called index.js.

We will setup a initial home route that will display some message when the server is loaded and running.

we will be using. a middleware that will return our entry in json format

we will be creating 5 separate routes to carry out the CRUD functions via REST API

we will tell set a port where our server will run and listen for any user inputs

Below is the full code covering all these concepts , in index.js file

import express from 'express'; import {getUsers, getUserByID,deleteUser, AddorUpdateUser} from './/dynamodb.js'; const app = express(); // here we are telling express to use the json middleware app.use(express.json()); // this is the route that will be called when we go to the root of the server; a home page-route app.get('/',(req,res)=>{ res.send('Welcome to Local Server. Get ready to be amazed') }) // this is the route that will get all the users from the table // we are using async/await to handle the promises // we are using try/catch to handle the errors app.get('/users', async (req,res)=>{ try { const users = await getUsers(); res.json(users); } catch (error) { console.log(error); res.status(500).json({error:error.message}) } }) // this is the route that will get a user by id. need to pass the id as a parameter app.get('/users/:id', async (req,res)=>{ try { const users = await getUserByID(req.params.id); res.json(users); } catch (error) { console.log(error); res.status(500).json({error:error.message}) } }) // this is the route that will add or update a user app.post('/users', async(req,res)=>{ const user = req.body; try { const newUser = await AddorUpdateUser(user); res.json(newUser) } catch (error) { console.log(error); res.status(500).json({error:error.message}) } }) // this is the route that will edit an existing user. need to pass the id as a parameter app.put('/users/:id',async(req,res)=>{ const user = req.body; const {id} = req.params; user.id = id; try { const newUser = await AddorUpdateUser(user); res.json(newUser) } catch (error) { console.log(error); res.status(500).json({error:error.message}) } }) // this is the route that will delete a user app.delete('/users/:id', async(req,res)=>{ try { const user = await deleteUser(req.params.id); res.json(user) } catch (error) { console.log(error); res.status(500).json({error:err}) } }) // this is the port that the server will listen to // we are using the environment variable PORT if it is available, if not we are using 8080 const port = process.env.PORT || 8080; // here we are telling the server to listen to the port app.listen(port,()=>{ console.log(`Server is running on port ${port}`) })

Below is the snapshot of GetAllUsers returned in our server

{ "Items": [ { "email": "bellawati@gmail.com", "id": "2", "name": "Bella koirala", "gender": "female" }, { "email": "test@email.com", "id": "1", "name": "testing tester", "gender": "male" } ], "Count": 2, "ScannedCount": 2 }

Happy Coding !

This post was last updated on: March 23, 2023

Back