Hanlu's Code Log

Full-stack developer | Open source contributor | Tech enthusiast

Setting Up a Node.js REST API with Express

In this tutorial, we will walk through the process of setting up a basic RESTful API using Node.js and Express. This API will allow us to perform CRUD (Create, Read, Update, Delete) operations on a simple resource, backed by MongoDB as our database. Whether you're just starting out with backend development or brushing up your skills, this guide should help you build a solid foundation.

What is Express?

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for building both web and mobile applications. It simplifies tasks like routing, handling HTTP requests, and managing middleware, making it one of the most popular choices for creating REST APIs in the Node.js ecosystem.

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js and npm (Node Package Manager)
  • MongoDB (locally or via a service like MongoDB Atlas)
  • A code editor like Visual Studio Code

Step 1: Initialize Your Project

Create a new directory for your project and initialize it with npm:

mkdir express-api-demo
cd express-api-demo
npm init -y

Step 2: Install Required Packages

Install Express, Mongoose (for interacting with MongoDB), and other useful tools:

npm install express mongoose dotenv cors helmet morgan

We’re also installing:

  • dotenv – to load environment variables from a .env file.
  • cors – to enable Cross-Origin Resource Sharing.
  • helmet – to secure HTTP headers.
  • morgan – for logging HTTP requests during development.

Step 3: Set Up the Server

Create a file called server.js and add the following boilerplate code:

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
require('dotenv').config();

const app = express();

// Middleware
app.use(express.json());
app.use(cors());
app.use(helmet());
app.use(morgan('dev'));

// Simple route
app.get('/', (req, res) => {
    res.send('Hello from Express!');
});

// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI)
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.error(err));

// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Step 4: Create a Data Model

Create a folder called models, and inside it, create a file named Item.js:

const mongoose = require('mongoose');

const ItemSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    }
}, { timestamps: true });

module.exports = mongoose.model('Item', ItemSchema);

Step 5: Define Routes

Create a folder called routes, and inside it, create a file named itemRoutes.js:

const express = require('express');
const router = express.Router();
const Item = require('../models/Item');

// Get all items
router.get('/items', async (req, res) => {
    try {
        const items = await Item.find();
        res.json(items);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

// Create an item
router.post('/items', async (req, res) => {
    const item = new Item({ name: req.body.name });
    try {
        const newItem = await item.save();
        res.status(201).json(newItem);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
});

// Export routes
module.exports = router;

Then, import the routes in server.js:

const itemRoutes = require('./routes/itemRoutes');
app.use(itemRoutes);

Step 6: Test Your API

You can now start the server using:

node server.js

Use Postman or curl to test your endpoints:

  • GET http://localhost:5000/items
  • POST http://localhost:5000/items with JSON body: { "name": "Test Item" }

Conclusion

Congratulations! You've successfully created a fully functional REST API using Node.js and Express. Along the way, you learned how to connect to MongoDB, define models, set up routes, and handle CRUD operations. From here, you can expand your API with authentication, validation, pagination, and more advanced features.

Thanks for following along. Keep building, keep learning!