Node js Rest API

thirdearnest123

thirdearnest123

Posted on July 5, 2024

Node js Rest API

Image descriptionCreating 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. npm is included with Node.js.

Install MongoDB

Download and install MongoDB from mongodb.com.

2. Create a New Project

  1. Initialize a new Node.js project:

    mkdir mern-rest-api
    cd mern-rest-api
    npm init -y
    
  2. Install dependencies:

    npm install express mongoose body-parser cors
    npm install --save-dev nodemon
    
  3. Install additional tools:

    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:

    mkdir src
    cd src
    mkdir config controllers models routes
    touch server.js
    
  2. Set up the server.js file:

    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:

    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:

    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:

    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:

    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:
Enter fullscreen mode Exit fullscreen mode
    ```json
    {
        "name": "thirdearnest123",
        "email": "thirdearnest123@example.com",
        "password": "password123"
    }
    ```
Enter fullscreen mode Exit fullscreen mode

Useful Resources

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.

💖 💪 🙅 🚩
thirdearnest123
thirdearnest123

Posted on July 5, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Node js Rest API
node Node js Rest API

July 5, 2024