Nairobi, Kenya

Building a simple REST API in node and express

Building a simple REST API in node and express

Hello in this tutorial today we are going to build a simple server-less REST API using nodeJS and Express

A server-less app means we are not going to store our data on a database

REST defines a set of conventions for creating HTTP services:

HTTP(Hyper Text Transfer Protocal) supports communictaion between the client and the web browsers

  • POST: to create a resource
  • PUT: to update it
  • GET: to read it
  • DELETE: to delete it

Express is an optimized web framework for building web servers.

what you need to have for this tutorial

  1. NodeJs
  2. Postman
  3. Code Editor
  4. Command Line Interface or Terminal

Lets start

1. Install the requirements

To install node click here node comes in hand with npm(node package manager).

To install postman click here.

Make sure you you have a code editor of your choice installed on your computer.

To verify whether node is installed enter the following commands in the terminal.

node -v
//the following comand will pop up v15.14.0 - the current version installed
npm -v
//the following comand will pop up 7.7.6 - the current version installed

2. Set up the project and initialize our app

Now lets set up our project create a directory and open it using the terminal in my case i have


C:\Users\LENOVO\Desktop\resturant>
//returant is my directory

Now lets initialize our app by typing the following command in the project folder in the terminal This will create a package.json file on the your folder

npm init -y

The package.json file should look like this

{
  "name": "resturant",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

For my case i have resturant as the default project name Learn more on package.json file here

3. Install Express and create our files

Now lets install express by typing the following command

npm install express --save

Now lets create our app,Create an index.js file on your root folder

Then add the code below

//dependencies we need

const express = require('express')
const app = express()

//start the server

const port = process.env.PORT || 3000

app.listen(port, ()=> console.log(`running on port ${port}`))

Congratulations we have built our web server and running on the port 3000 to run your app run the command below

node index.js

you will see a message on the terminal as

running on port 3000

Lets create an array of object named meals,we are going to use the data in there in our API , see the code below which is part of our index.js file

const meals = [

{id: 1, name: 'pizza'},
{id: 2, name: 'tea'},
{id: 3, name: 'cocktail'},
{id: 4, name: 'chicken'}

]

For this tutorial today we are going to handle the GET and POST methods

4. Handling GET method

Now lets create a simple get request to retrieve the list of all meals, see the code below

app.get("/api/meal", (req, res) => {
 res.send(meals)
});

Now open your postman and enter the following url with a get request Follow my previous tutorial here on configuring postman

localhost:3000/api/meal localhost

The post man will show the following interface

localhost:3000/api/meal

You can now retrieve the list of meals available in a restaurant

5. Handling POST method

The use of the POST method is to create a resource on the server

This may include submitting a form,uploading a file to the web server

The POST method is used to send data to the server from an HTTP client

Lets get to the post method,we will ad some data to our API , the data added can only be viewed in the postman since its serverless and hence will not be saved for retrivial

app.post('/api/meal',(req,res)=> {

const meal = {
        id: meals.length + 1,
        name : req.body.name 
    };

    meals.push(meal)
    res.send(meal)

});

add this line to enable parsing of json object in the body request

app.use(express.json())

Go to postman and enter the url with a post request try sending in some raw data in the body , your data should look like this

{

    "name" : "ian"

}

Great work done you can now retrieve and send data on your API

The whole program looks like this

const express = require('express')
const app = express();
app.use(express.json())
//array of data

const meals = [

{id: 1, name: 'pizza'},
{id: 2, name: 'tea'},
{id: 3, name: 'cocktail'},
{id: 4, name: 'chicken'}

]

//post method
app.post('/api/meal',(req,res)=> {

const meal = {
        id: meals.length + 1,
        name : req.body.name 
    };

    meals.push(meal)
    res.send(meal)

});


//get method
app.get("/api/meal", (req, res) => {
 res.send(meals)
});

const port = process.env.PORT || 3000

app.listen(port, ()=> console.log(`running on port ${port}`))

Great work done!!! That was just a simple exercise to jump start you with the REST API you can do more research and find more.

Find the whole program here follow this link for more