Codementor Events

Building a simple API with Nodejs, Expressjs and JS Data structure to persist data - 1

Published Jul 29, 2018Last updated Feb 21, 2019
Building a simple API with Nodejs, Expressjs and JS Data structure to persist data - 1

I met someone recently with some difficulties understanding node js and expressjs. So I decided to put this together with the hope that it will help somebody.

In this tutorial, you'll learn how to build a simple API with Nodejs using ES6. What is Nodejs, you may ask- According to Wikipedia Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside the browser. It is a javascript runtime built on Chrome V8 Javascript Engine. Simply put Nodejs give us the ability to write backend code in Javascript.

What we will build?

You'll learn how to build a reflection API - A reflection app gives users the ability to reflect and document daily successes, failures and a plan on what to do better the next day.

Success is not final; failure is not fatal: It is the courage to continue that counts. -- Winston S. Churchill

Getting Started

Before you continue, install the following on your system if you don't already have

  • Nodejs
  • NPM - NPM is a package manager for Javascript

On your terminal, run the following command to check if Nodejs and npm are successfully installed on your system

Screen Shot 2018-07-28 at 10.31.55 PM.png

Project Setup

  • Create a new project directory on your system, you can call node_express_tutorial
  • Change working directly to the project and run npm init on your terminal or command prompt if you're using a window system - Running npm init will prompt you with some questions to help set up your project

Screen Shot 2018-07-28 at 9.58.41 PM.png

What that is done, you should see package.json file in your project and it contains basic information about your project.

{
  "name": "node_express_tutorial",
  "version": "1.0.0",
  "description": "node express tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Olawale Aladeusi",
  "license": "ISC"
}

Next, let's install all the package dependencies that we'll need to build the project

  • expressjs - Expressjs is a nodejs web application framework that gives us the ability to create quick and easy APIs.
  • momentjs - This gives us the ability to validates and manipulates dates.
  • uuid npm package](https://www.npmjs.com/package/uuid)
  • babeljs - Since we'll be writing all our JavaScript code using ES6, babeljs will help in converting our ES6 codes to ES5.
  • babel watch - This is needed for development. One thing that babel watch package does is to compile our code and reload the server each time we make changes to our code.

Run the following command to install all the above packages

$ npm install --save express moment uuid
$ npm install --save-dev babel-cli babel-preset-env babel-watch

If all went well, you should see something similar to this

Screen Shot 2018-07-28 at 10.55.53 PM.png

and your package.json file should contain the following

{
  "name": "node_express_tutorial",
  "version": "1.0.0",
  "description": "node express tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Olawale Aladeusi",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "moment": "^2.22.2"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-watch": "^2.0.7"
  }
}

You'll notice that express and moment is under dependencies, that is because those are needed by the time we deploy our code to production. babel-cli, babel-preset-env and babel-watch are only needed during development.
You should also see a new folder called node_modules in the project root directory - This folder contains the source code of the package we downloaded.

Project Structure

Set up your project structure using the following format

-node_express_tutorial
  |-package.json
  |-.babelrc
  |-server.js
  |-src
    |-controllers
      |-Reflection.js
    |-models
      |-Reflection.js

Server SetUp

Add the following code to server.js

alt

From the code above, we imported express and set up a new express instance const app = express(). We set up a new express.json() middleware - this is needed to get access to request body. Lastly, we set up a sample endpoint to test if the server is working.
Note: express.json() is only available in express version 4.16.0 and above

If you run the server using node server.js command, you'll get an error

Screen Shot 2018-07-28 at 11.51.31 PM.png

Don't worry, you're getting the error because nodejs runtime cannot understand some of the ES6 features we used - e.g import. In the next section we will set up babel - babel will help us compile the code to ES5 that nodejs runtime can understand.

Set Up babel

In the project root directory, create a new file and name it .babelrc and add

{
  "presets": ["env"] 
}

Next, open package.json and add "build": "babel server.js --out-dir build" under script property.

{
  "name": "node_express_tutorial",
  "version": "1.0.0",
  "description": "node express tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel server.js --out-dir build"
  },
#################
# existing code #
################
}

Now, run the following command

$ npm run build

If the above command was successful you will notice that a new build folder has been created in the project directory. Open it and click on server.js - notice the original code has been compiled down to es5. So, running the server.js inside build folder should successfully run your server without error.

$ node build/server.js

Screen Shot 2018-07-29 at 12.02.12 AM.png

To test if our sample endpoint is working, navigate to http://localhost:3000/ on the browser.

Screen Shot 2018-07-29 at 12.03.48 AM.png

One last thing we need to do in this section is setup babel-watch. Currently, if you make any changes to server.js, you'll need to run a new build and restart the server before your changes will reflect. Going through the build process and restarting server does not make sense for development purpose. This is where babel-watch came to the rescue, as the name implies, babel-watch watch over any changes you made in your code and automatically compile and restart your server.
Add "dev-start": "babel-watch server.js" to your package.json under script.
Running npm run dev-start should start your server
Screen Shot 2018-07-29 at 12.10.42 AM.png

Set up Reflection Model

To make things simple, we'll not make use of database for our project. Instead we'll use JavaScript Objects to persist user's data.
Open src/models/Reflection.js and add the following code

alt

We created Reflection class with five methods create() - to create a new reflection, findOne() - find one reflection, findAll() - find all reflections, update() - update a reflection and delete() - delete a reflection. Each reflection object will contains six propeties id, success, lowPoint, takeAway, createdDate and modifiedDate. We use uuid.v4() to set the default reflection id, moment to set default values for createdDate and modifiedDate.

Set up Controller and Endpoints

The following endpoints will be defined

  • Create a Reflection - POST /api/v1/reflections
  • Get All Reflections - GET /api/v1/reflections
  • Get A Reflection - GET /api/v1/reflections/:id
  • Update A Reflection - PUT /api/v1/reflections/:id
  • Delete A Reflection - DELETE /api/v1/reflections/:id

But first, let's set up our reflection controller, to do that add the following code to src/controllers/Reflection

alt

We created Reflection object that contains create - to create a new reflection, getAll - get all reflections, getOne - get one reflection, update - update a reflection and delete - delete a reflection properties.

Finally, let's defined our endpoints, open server.js and add the following code

import Reflection from './src/controllers/Reflection';

app.post('/api/v1/reflections', Reflection.create);
app.get('/api/v1/reflections', Reflection.getAll);
app.get('/api/v1/reflections/:id', Reflection.getOne);
app.put('/api/v1/reflections/:id', Reflection.update);
app.delete('/api/v1/reflections/:id', Reflection.delete);

The above defines all our five endpoints, each connecting to it's respective controller method.

Test on POSTMAN

Use the following command to run the server

$ npm run dev-start

You can use POSTMAN to test all our endpoints

  • Create A Reflection
    Screen Shot 2018-07-29 at 2.08.42 AM.png

  • Get All Reflections
    Screen Shot 2018-07-29 at 2.10.06 AM.png

  • Get A Reflection
    Screen Shot 2018-07-29 at 2.10.50 AM.png

  • Update A Reflection
    Screen Shot 2018-07-29 at 2.11.40 AM.png

  • Delete A Reflection
    Screen Shot 2018-07-29 at 2.12.15 AM.png

Conclusion

In this tutorial, we've learned how to setup node expressjs server, how to setup models using object and how to create basic endpoints.

Drop your questions and comments. Don't forget to like this post if you learned one or two things.

Discover and read more posts from Olawale Aladeusi
get started
post commentsBe the first to share your opinion
Izabayo Blaise
4 years ago

how would I do it
if I would wanna use HTML to do the controls

maybe delete a file
or display the data from the fetch API?

Jose L. Velez
5 years ago

Hello, very nice tutorial. I am having a problem with the controller part however. It imports ReflectionModel from '../models/Reflection' but what/where is ReflectionModel? Is that the class being defined in the Reflection.js controller file? Is it not called Reflection?

Thanks!

Seun Isaiah
5 years ago

Well documented but i seem to be getting errors.

TypeError: Cannot read property ‘success’ of undefined
at Reflection.success [as create] (C:\Users\ 1\Desktop\nodeTut\node_express_tut\src\mout\node_express_tut\src\models/Reflection.js:19:21) controllers/Reflection.js:
at create (C:\Users\Desktop\nodeTut\node_express_tut\src\eTut\node_express_tut\nodecontrollers/Reflection.js:13:40)

Show more replies