Ad Code

Ticker

6/recent/ticker-posts

How to create rest api in nodejs

How to create rest api in nodejs

NodeJs is an open source server environment which is free and runs on various platforms like Windows, Linux, Unix and Mac OS X etc. Its usage Javascript on the server. Today Javascript is the most popular programming language its usage many type of application development like web, app etc.

How to create api in nodejs.

Its usage nodejs environment and mongodb installed on locally. Create package.json file using following command run on the project directory.

How to create rest api in nodejs
Run command:- npm init -y

This command generate default package on nodejs in your current directory. After this add express and body-parser.

npm install express body-parser mongoose

Express:- Node.js web application framework.
Body-Parse:- it is a middleware which is parse the request stream and expose into req.body.
Mongoose:- is a MongoDB object modeling tool.

After this create a file server.js in project directory using following code.
const express = require("express");
const bodyParser = require("body-parser");

// create express app
const app = express();

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// parse requests of content-type - application/json
app.use(bodyParser.json());

// define a simple route
app.get("/", (reqres=> {
    res.send("Welcome to nodejs application.");
});

// listen for requests
app.listen(3000, () => {
    console.log("Server is listening on port 3000.");
});

After this code edit package.json add script start

{
    "name""blogs",
    "version""1.0.0",
    "description""",
    "main""index.js",
    "scripts": {
        "test""echo \"Error: no test specified\" && exit 1",
        "start": "node server.js"
    },
    "keywords": [],
    "author""",
    "license""ISC",
    "dependencies": {
        "body-parser""^1.19.0",
        "express""^4.17.1",
        "mongoose""^5.9.10"
    }
}

run command for running npm start


How to create rest api in nodejs

run browser with this url:- http://localhost:3000 view the following output


How to create rest api in nodejs

this is simple string display in the browser.

after this example use database for api request like GET/POST/PUT/DELETE then add some code in server.js after body-parser call.

const bodyParser = require("body-parser");
const mongoose = require("mongoose");

//database connection
mongoose.Promise = global.Promise;

// Connecting to the database
mongoose
    .connect("mongodb://localhost:27017/demo", {
        useNewUrlParser: true,
        useFindAndModify: false,
        useCreateIndex: true,
        useUnifiedTopology: true,
    })
    .then(() => {
        console.log("Successfully connected to the database");
    })
    .catch((err=> {
        console.log("Could not connect to the database. Exiting now..."err);
        process.exit();
    });

Add user model using mongoose

Add new folder in root directory name is models, inside this folder add User.js file and put the following code.

'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var UserSchema = new Schema({
    name: { type: String },
    email: { type: String },
    mobile: { type: String },
    address: { type: String }
}, { timestamps: true });

module.exports = mongoose.model('User'UserSchema);

after this model add server.js api like get list , get by id, post, put and delete route before app.listen segment

// import user model
const User = require('./models/User');

// get user lists
app.get("/user", (reqres=> {
    User.find({}, (erruser=> {
        if (errreturn res.status(400).json(err);
        res.json(user);
    });
});

//get user by id
app.get("/user/:id", (reqres=> {
    User.findById(req.params.id, (erruser=> {
        if (errreturn res.status(400).json(err);
        res.json(user);
    });
});

// insert user
app.post("/user/", (reqres=> {
    var user = new User(req.body);
    user.save((erruser=> {
        if (errreturn res.status(400).json(err);
        res.json(user);
    });
});

//update user by id
app.put("/user/:id", (reqres=> {
    User.findByIdAndUpdate(req.params.idreq.body, { new: true }, (erruser=> {
        if (errreturn res.status(400).json(err);
        res.json(user);
    });
});

//delete user by id
app.delete("/user/:id", (reqres=> {
    User.findByIdAndRemove(req.params.id, (erruser=> {
        if (errreturn res.json(err);
        res.json(user);
    });
});

save and run application. Use postman for api testing.

1. Insert data using api
In this use post method using postman, the data insert into mongodb database the server.js file add mongoose connection database automatically careated and users document (table).
use following formate json data for insertion user.

{
    "name""Wpopener",
    "email""wpopener@example.com",
    "mobile""1234567867",
    "address""Delhi -000002"
}

and set into row and use json structure of the postman body please set header content-type application/json, url is http://localhost:3000/user

2. Get users lists
use http://localhost:3000/user with get method into postman, if you want to run on browser you can run this url.

[{
        "_id": "5ea6f1ffc78bda2a306b188a",
        "name": "Priya Digital Technology",
        "email": "priya@example.com",
        "mobile": "1234567890",
        "address": "Delhi -000000",
        "createdAt": "2020-04-27T14:53:51.102Z",
        "updatedAt": "2020-04-27T14:53:51.102Z",
        "__v": 0
    },
    {
        "_id": "5ea6f221c78bda2a306b188b",
        "name": "Wpopener",
        "email": "wpopener@example.com",
        "mobile": "1234567867",
        "address": "Delhi -000002",
        "createdAt": "2020-04-27T14:54:25.231Z",
        "updatedAt": "2020-04-27T14:54:25.231Z",
        "__v": 0
    }
]

3. Get user by id
use url http://localhost:3000/user/5ea6f1ffc78bda2a306b188a in browser or get method in postman

{
    "_id""5ea6f1ffc78bda2a306b188a",
    "name""Priya Digital Technology",
    "email""priya@example.com",
    "mobile""1234567890",
    "address""Delhi -000000",
    "createdAt""2020-04-27T14:53:51.102Z",
    "updatedAt""2020-04-27T14:53:51.102Z",
    "__v"0
}

4. Update user
When update user same as the insert method except url and and method. Update user url is http:localhost:3000/user/5ea6f1ffc78bda2a306b188a and method is PUT run in postman and update data in the previous data. Its update only given user id in url.

5. Delete user
In this use url http:localhost:3000/user/5ea6f1ffc78bda2a306b188a and method delete in postman to delete data only given url id data.

Post a Comment

0 Comments

Ad Code