DEV Community

Cover image for Build Your Own API using node and express
Kirti
Kirti

Posted on

Build Your Own API using node and express

Hey everyone, I am here again with the new article in this we will be building our very own API using node and express. Let's start with the setup first in which we initialize our backend JavaScript application.

npm init -y
Enter fullscreen mode Exit fullscreen mode

Now we do need to express well so let us install express as well.

npm install --save express
Enter fullscreen mode Exit fullscreen mode

Now to use normal or new import statements go to package.json and make an entry as

 "name": "crud_api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module", // this line 
Enter fullscreen mode Exit fullscreen mode

Now, let's make an index.js, I have attached the code below explaining each line of it.

import express from "express";
// can also write const express = require ('express');
import bodyParser from "body-parser";
// bodyParser allows us to take incoming post request bodies
const app =express();
// Now our whole application lies in this little variable
const PORT = 4000;
// specifying port of our application , you can choose any port 
app.use(bodyParser.json)
//it says we are going to use json data in our body
app.listen(PORT, () =>console.log(`Server running on port: http://localhost:${PORT}`)); 
//To listen to this port and a callback function 
Enter fullscreen mode Exit fullscreen mode

For stopping the server use "Ctrl+C"
Wait.. but how can we see the changesπŸ€” because by this time we can only see the server running on the following port, or the things we console what about the changes done on the client-side. Nodemon is the solution let's quickly install Nodemon.

 npm install --save -dev nodemon
Enter fullscreen mode Exit fullscreen mode

Now to run our Nodemon let's quickly set up the start scripts in package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
Enter fullscreen mode Exit fullscreen mode

Yahaya!!πŸ˜‡ We are done with all the setup of our basic express server.
Now, let's just have a quick look at what some terms mean and do.

GET It finds all the users. example -> /user
POST Creates a user. example -> /user
GET Find user detail by id example-> /user/:id
DELETE** Deletes a user example-> **/user/:id
PATCH Updates a user example-> /user/:id

Let's start with our get operation first, Let's create a folder with name controllers and inside it a users.js file.

let users =[]; // an empty array that is the data 

// THIS IS GET OPERATION
//request and response are the parameters passed in this function
export const getUser=(req,res) =>{
// printing the users 
    console.log(`Users in database: ${users}`);
    res.send(users);// sending data from server to client 
}
Enter fullscreen mode Exit fullscreen mode

Now, for the post-operation, one can note that we can have unique ids for each user as it would help us to delete and update the database in further command. so, let's just install a node package

npm i uuid
Enter fullscreen mode Exit fullscreen mode

The post function

export const createUser = (req, res) => {   
    const user = req.body;
   //In the below statement we are spreding the already users object and adding id as well  
    users.push({...user, id: uuid()});
    console.log(`User [${user.username}] added to the database.`);
};
Enter fullscreen mode Exit fullscreen mode

Now, let's see how to get a particular user from the database

//THIS IS GET A PARTICULAR USER WITH A ID
export const getUser = (req, res) => {
    res.send(req.params.id)
};
Enter fullscreen mode Exit fullscreen mode

For deleting a particular users

// FOR deleting a particular user
export const deleteUser = (req, res) => { 
    console.log(`user with id ${req.params.id} has been deleted`);

    users = users.filter((user) => user.id !== req.params.id);
};
Enter fullscreen mode Exit fullscreen mode

For updating a particular value of a user

//Update a particular user
export const updateUser =  (req,res) => {
    const user = users.find((user) => user.id === req.params.id);

    user.username = req.body.username;
    user.age = req.body.age;

    console.log(`username has been updated to ${req.body.username}.age has been updated to ${req.body.age}`)
};
Enter fullscreen mode Exit fullscreen mode

Now, let's have a look at the routes where the above operations will be directed to.

import express from 'express';
import {createUser, getUsers, getUser, deleteUser, updateUser} from '../Controllers/users.js'

const router = express.Router();

router.get('/',getUsers);
router.post('/',createUser);
router.get('/:id',getUser);
router.delete('/:id',deleteUser);
router.patch('/:id',updateUser);

export default router;
Enter fullscreen mode Exit fullscreen mode

index.js

import express from "express";
//  can also write const express = require ('express');
import bodyParser from "body-parser";
// bodyParser allows us to take incoming post request bodies
import usersRoutes from "./routes/routes.js"
const app =express();
// Now our whole appliaction lies in this little variable
const PORT = 5000;
// specifying port of our aplication , you can choose any port 
app.use(bodyParser.json)
//it says we are going to use json data in our body
app.use("/users", usersRoutes);

app.get("/", (req, res) => res.send("Welcome to the Users API!"));

app.all("*", (req, res) =>res.send("You've tried reaching a route that doesn't exist."));

app.listen(PORT, () =>console.log(`Server running on port: http://localhost:${PORT}`)); 
//To listen to this port and a callback function 
Enter fullscreen mode Exit fullscreen mode

YAYAA!!! we created our API with crud functionality, for testing you can use POSTMAN which is free will attach the link below for the same with the GitHub link πŸ˜„πŸ˜„.
GitHub
Postman

Discussion (0)