Test Node js ( API Creating and Test in Postman )

 


BACKEND MACHINE TEST

F.M: 50 TIME: 1 HR 30 MIN

Question: 1

You have a develop API with CRUD OPERATION and test that API using POSTMAN

TOOL:

NOTE: CREATE A NEW APP FOR THE API CREATION AND INSTALL THE DEPENDENCY REQUIRED

FOR API CREATION.

NOTE THE BELOW POINTS:

 CREATE A MODAL SCHEMA FOR RAILINFO :

 Fields :

 { _id:’’ , train_no:’’ , train_name:’’ ,

src_station:’’,dest_station:’’,platform_no:’’,dep_time:’’,arr_time:’’}

 CREATE THE CONTROLLER FOR THE BELOW OPERATIONS ON API :

 FETCH ALL TRAIN INFO

 FIND SPECIFIC TRAIN INFO based on src_station , dest_station

 INSERT TRAIN INFO

 UPDATE TRAIN INFO based on train_no

 DELETE TRAIN INFO based on train _id

 CREATE THE PROPER ROUTING FOR API.

 TEST EACH ENDPOINTS USING POSTMAN and provide the screenshots

Attached.



 Task Overview:


You need to develop an API that supports CRUD operations (Create, Read, Update, Delete) for train information. The API will be tested using the Postman tool. The steps below will guide you through creating a new application, defining the data schema, implementing the API, setting up routes, and testing with Postman.


 Step 1: Set Up a New Project


a) Initialize a New Project


Depending on the language and framework you prefer, initialize a new project. Here, I'll guide you through the process using Node.js with Express.js and MongoDB as the database.


```bash

mkdir railinfo-api

cd railinfo-api

npm init -y

npm install express mongoose body-parser

```


b) Create Project Structure


Create folders and files for the model, controller, and routes.


```bash

mkdir models controllers routes

touch app.js

```


 Step 2: Create a Model Schema for `RailInfo`


Define a schema that outlines the structure of your train information.


```javascript

// models/RailInfo.js

const mongoose = require('mongoose');


const railInfoSchema = new mongoose.Schema({

    train_no: { type: String, required: true },

    train_name: { type: String, required: true },

    src_station: { type: String, required: true },

    dest_station: { type: String, required: true },

    platform_no: { type: String, required: true },

    dep_time: { type: String, required: true },

    arr_time: { type: String, required: true }

});


const RailInfo = mongoose.model('RailInfo', railInfoSchema);

module.exports = RailInfo;

```


 Step 3: Create Controllers for CRUD Operations


Implement the logic for handling CRUD operations.


```javascript

// controllers/railController.js

const RailInfo = require('../models/RailInfo');


// Fetch All Train Info

exports.getAllTrainInfo = async (req, res) => {

    const trains = await RailInfo.find();

    res.json(trains);

};


// Find Specific Train Info based on src_station and dest_station

exports.getTrainByRoute = async (req, res) => {

    const { src_station, dest_station } = req.query;

    const trains = await RailInfo.find({ src_station, dest_station });

    res.json(trains);

};


// Insert Train Info

exports.createTrainInfo = async (req, res) => {

    const newTrain = new RailInfo(req.body);

    await newTrain.save();

    res.json(newTrain);

};


// Update Train Info based on train_no

exports.updateTrainInfo = async (req, res) => {

    const { train_no } = req.params;

    const updatedTrain = await RailInfo.findOneAndUpdate({ train_no }, req.body, { new: true });

    res.json(updatedTrain);

};


// Delete Train Info based on train_id

exports.deleteTrainInfo = async (req, res) => {

    const { id } = req.params;

    await RailInfo.findByIdAndDelete(id);

    res.json({ message: 'Train info deleted' });

};

```


 Step 4: Set Up Routing


Define the routes that connect the HTTP requests to the appropriate controller functions.


```javascript

// routes/railRoutes.js

const express = require('express');

const router = express.Router();

const railController = require('../controllers/railController');


router.get('/trains', railController.getAllTrainInfo);

router.get('/trains/search', railController.getTrainByRoute);

router.post('/trains', railController.createTrainInfo);

router.put('/trains/:train_no', railController.updateTrainInfo);

router.delete('/trains/:id', railController.deleteTrainInfo);


module.exports = router;

```


 Step 5: Set Up the Application


Integrate everything in your main application file.


```javascript

// app.js

const express = require('express');

const mongoose = require('mongoose');

const bodyParser = require('body-parser');

const railRoutes = require('./routes/railRoutes');


const app = express();

app.use(bodyParser.json());


mongoose.connect('mongodb://localhost/railinfo', {

    useNewUrlParser: true,

    useUnifiedTopology: true,

    useFindAndModify: false

});


app.use('/api', railRoutes);


app.listen(3000, () => {

    console.log('Server is running on port 3000');

});

```


 Step 6: Test the API Using Postman


1. Fetch All Train Info

   - Method: `GET`

   - URL: `http://localhost:3000/api/trains`

   - Response: Should return all train records.


2. Find Specific Train Info

   - Method: `GET`

   - URL: `http://localhost:3000/api/trains/search?src_station=XYZ&dest_station=ABC`

   - Response: Should return trains matching the specified source and destination stations.


3. Insert Train Info

   - Method: `POST`

   - URL: `http://localhost:3000/api/trains`

   - Body (JSON):

     ```json

     {

         "train_no": "12345",

         "train_name": "Express Train",

         "src_station": "Station A",

         "dest_station": "Station B",

         "platform_no": "1",

         "dep_time": "10:00",

         "arr_time": "14:00"

     }

     ```

   - Response: Should return the newly created train record.


4. Update Train Info

   - Method: `PUT`

   - URL: `http://localhost:3000/api/trains/12345`

   - Body (JSON):

     ```json

     {

         "train_name": "Super Express",

         "platform_no": "2"

     }

     ```

   - Response: Should return the updated train record.


5. Delete Train Info

   - Method: `DELETE`

   - URL: `http://localhost:3000/api/trains/60f0c2e5a47e6c1a88e00000`

   - Response: Should confirm the deletion.


 Step 7: Provide Screenshots


Capture screenshots of each Postman request and response, and compile them into a document. Annotate the screenshots if needed, to explain the output of each API request.


This completes the setup and testing of the CRUD API for the `RailInfo` system.

Comments

Popular posts from this blog

IMPORTANT INTERVIEW RELATED QUESTION

Survey Paper

C++ Interview Questions

Git Cheat Sheet: A Beginner to Intermediate Guide

Java Interview Questions

INTERVIEW QUS ON AUTOMATA

OPERATION RESEARCH SYLLABUS

CPU CACHE MEMORY

MAKING POWERPOINT SLIDES