Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 25, 2021 07:39 am GMT

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

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

npm install --save express

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 

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 bodiesconst app =express();// Now our whole application lies in this little variableconst 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 bodyapp.listen(PORT, () =>console.log(`Server running on port: http://localhost:${PORT}`)); //To listen to this port and a callback function 

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

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"  },

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 functionexport const getUser=(req,res) =>{// printing the users     console.log(`Users in database: ${users}`);    res.send(users);// sending data from server to client }

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

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.`);};

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

//THIS IS GET A PARTICULAR USER WITH A IDexport const getUser = (req, res) => {    res.send(req.params.id)};

For deleting a particular users

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

For updating a particular value of a user

//Update a particular userexport 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}`)};

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;

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 bodiesimport usersRoutes from "./routes/routes.js"const app =express();// Now our whole appliaction lies in this little variableconst 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 bodyapp.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 

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


Original Link: https://dev.to/kirtisingh3008/build-your-own-api-using-node-and-express-3g3e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To