How to Make API using NodeJS and Express

How to Make API using NodeJS and Express

Created by eneaslari 19/9/2023

nodejs

Setting Up the Project

  1. Initial Setup:

    mkdir node-express-api
    cd node-express-api
    npm init -y
    
  2. Install Required Packages:

    npm install express mongoose
    

Folder Structure

  • node-express-api
    • models
    • controllers
    • routes
    • app.js

Models

1. User Model (models/user.js)

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String,
});

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

2. Product Model (models/product.js)

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
    name: String,
    price: Number,
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }
});

module.exports = mongoose.model('Product', productSchema);

3. Category Model (models/category.js)

const mongoose = require('mongoose');

const categorySchema = new mongoose.Schema({
    name: String,
});

module.exports = mongoose.model('Category', categorySchema);

Controllers

1. User Controller (controllers/userController.js)

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

exports.createUser = async (req, res) => {
    try {
        const user = new User(req.body);
        await user.save();
        res.status(201).json(user);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
};

2. Product Controller (controllers/productController.js)

const Product = require('../models/product');

exports.createProduct = async (req, res) => {
    try {
        const product = new Product(req.body);
        await product.save();
        res.status(201).json(product);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
};

3. Category Controller (controllers/categoryController.js)

const Category = require('../models/category');

exports.createCategory = async (req, res) => {
    try {
        const category = new Category(req.body);
        await category.save();
        res.status(201).json(category);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
};

Routes

Routes Setup (routes/index.js)

const express = require('express');
const userController = require('../controllers/userController');
const productController = require('../controllers/productController');
const categoryController = require('../controllers/categoryController');

const router = express.Router();

router.post('/users', userController.createUser);
router.post('/products', productController.createProduct);
router.post('/categories', categoryController.createCategory);

module.exports = router;

Bringing It All Together

app.js

const express = require('express');
const mongoose = require('mongoose');
const routes = require('./routes');

const app = express();

mongoose.connect('mongodb://localhost:27017/node-express-api', { useNewUrlParser: true, useUnifiedTopology: true });

app.use(express.json());
app.use('/api', routes);

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

Now, after setting up the above structure, you have the basic building blocks for an API in Node.js and Express. You can run the app with:

node app.js

Remember, this is a basic structure, and there's much more you can do, such as adding error handling, validation, authentication, etc. I hope this provides a solid starting point!

More to read


New Year, New Code: My Developer Resolutions for the Year
29/12/2024

In this blog post, I share my New Year's resolutions as a developer: posting more about my work on social media, writing more articles, and finally finishing and publishing a game. Plus, I offer practical tips on setting realistic and achievable goals to help fellow developers kick off the year with purpose!

Bad Practices in JavaScript: Common Pitfalls and How to Avoid Them 🚫
28/12/2024

JavaScript is like the Swiss Army knife of web development—it’s everywhere, from tiny website features to massive, complex web apps. But with great power comes... well, the chance to make a mess! Its flexibility and loose rules make it super easy to use, but also super easy to misuse.

Bad Practices in Express.js Apps: Common Mistakes and How to Avoid Them 🚫
27/12/2024

Express.js is one of the most popular frameworks for building web applications with Node.js. It's fast, minimal, and incredibly flexible. However, this flexibility often leaves room for mistakes, especially for developers new to backend development. In this post, we’ll cover some of the most common bad practices in Express.js, why they’re problematic, and how you can avoid them.

Understanding `null` vs. `undefined` in JavaScript and Best Practices for Mongoose Schemas
18/10/2024

We’ll dive into the differences between `null` and `undefined` in JavaScript, how to declare nullable fields in Mongoose schemas, and best practices for creating and managing schemas.