Node js Rest API
Tags: node, restapi, mern
Published: 2024-07-05 06:19:05


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uk5ml7vk5ey8glkjaq38.png)Creating a REST API using Node.js in the MERN stack involves several steps, including setting up MongoDB, creating the backend with Express, and using tools like Postman to test the API. Here's a detailed guide to help you through the process:

### 1. Set Up Your Environment

#### Install Node.js and npm

Download and install Node.js from [nodejs.org](https://nodejs.org/). npm is included with Node.js.

#### Install MongoDB

Download and install MongoDB from [mongodb.com](https://www.mongodb.com/try/download/community).

### 2. Create a New Project

1. **Initialize a new Node.js project:**
    ```sh
    mkdir mern-rest-api
    cd mern-rest-api
    npm init -y
    ```

2. **Install dependencies:**
    ```sh
    npm install express mongoose body-parser cors
    npm install --save-dev nodemon
    ```

3. **Install additional tools:**
    ```sh
    npm install express-validator
    ```

### 3. Set Up MongoDB

1. **Start MongoDB:**
    - On Windows: Run `mongod` in your terminal.
    - On Mac: You can use `brew services start mongodb-community`.

2. **Create a new database and collection:**
    - Use MongoDB Compass or the MongoDB shell to create a new database (e.g., `mern_db`) and a collection (e.g., `users`).

### 4. Create the Express Server

1. **Create the directory structure:**
    ```sh
    mkdir src
    cd src
    mkdir config controllers models routes
    touch server.js
    ```

2. **Set up the `server.js` file:**
    ```javascript
    const express = require('express');
    const mongoose = require('mongoose');
    const bodyParser = require('body-parser');
    const cors = require('cors');

    const app = express();

    // Middleware
    app.use(bodyParser.json());
    app.use(cors());

    // MongoDB connection
    mongoose.connect('mongodb://localhost:27017/mern_db', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });

    mongoose.connection.once('open', () => {
        console.log('Connected to MongoDB');
    });

    // Routes
    const users = require('./routes/users');
    app.use('/api/users', users);

    const PORT = process.env.PORT || 5000;

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

### 5. Create Models

1. **Create `models/User.js`:**
    ```javascript
    const mongoose = require('mongoose');

    const UserSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true,
        },
        email: {
            type: String,
            required: true,
            unique: true,
        },
        password: {
            type: String,
            required: true,
        },
    });

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

### 6. Create Controllers

1. **Create `controllers/userController.js`:**
    ```javascript
    const User = require('../models/User');
    const { body, validationResult } = require('express-validator');

    // Get all users
    exports.getUsers = async (req, res) => {
        try {
            const users = await User.find();
            res.json(users);
        } catch (err) {
            res.status(500).json({ message: err.message });
        }
    };

    // Create a new user
    exports.createUser = [
        body('name').notEmpty().withMessage('Name is required'),
        body('email').isEmail().withMessage('Email is not valid'),
        body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'),

        async (req, res) => {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                return res.status(400).json({ errors: errors.array() });
            }

            const { name, email, password } = req.body;
            try {
                const user = new User({ name, email, password });
                await user.save();
                res.status(201).json(user);
            } catch (err) {
                res.status(500).json({ message: err.message });
            }
        },
    ];
    ```

### 7. Create Routes

1. **Create `routes/users.js`:**
    ```javascript
    const express = require('express');
    const router = express.Router();
    const userController = require('../controllers/userController');

    // Get all users
    router.get('/', userController.getUsers);

    // Create a new user
    router.post('/', userController.createUser);

    module.exports = router;
    ```

### 8. Test the API with Postman

1. **Start the server:**
    ```sh
    nodemon src/server.js
    ```

2. **Open Postman and create a new request:**

    - **GET** `http://localhost:5000/api/users` to fetch all users.
    - **POST** `http://localhost:5000/api/users` to create a new user. In the body, use the following JSON format:
        ```json
        {
            "name": "thirdearnest123",
            "email": "thirdearnest123@example.com",
            "password": "password123"
        }
        ```

### Useful Resources

- [Node.js](https://nodejs.org/)
- [Express.js](https://expressjs.com/)
- [MongoDB](https://www.mongodb.com/)
- [Postman](https://www.postman.com/)
- [Mongoose](https://mongoosejs.com/)
- [Express Validator](https://express-validator.github.io/docs/)

By following these steps, you will have a basic REST API setup using the MERN stack. You can further expand this by adding more features, authentication, and front-end integration.