API CRUD Operations with Node.js and Express: A Beginner’s Guide

API CRUD Operations with Node.js and Express: A Beginner’s Guide

Learn how to build a RESTful API with CRUD operations using Node.js, Express, and MongoDB. This beginner-friendly guide.

Introduction: My First API Challenge

When I first started working with backend development, I assumed CRUD operations were straightforward. After all, creating, reading, updating, and deleting data sounded easy. But when I began building real-world applications, I ran into problems. How do you structure your API? What happens if a request fails? How do you ensure your API is easy to maintain?

In this article, I will walk you through CRUD operations using Node.js, Express, and MongoDB. I will explain each step in detail so that even if you're a complete beginner, you'll understand how to build a RESTful API from scratch.


What is CRUD?

CRUD stands for Create, Read, Update, and Delete—the four basic operations performed on a database. Let's briefly explain what each operation does:

CRUD OperationHTTP MethodDescription
CreatePOSTAdds a new record to the database
ReadGETRetrieves existing records from the database
UpdatePUT or PATCHModifies an existing record
DeleteDELETERemoves a record from the database

When building an API, these operations allow users to interact with stored data in a structured way.


Setting Up the Project

Before we start coding, let's set up our project.

1. Initialize the Project

To create a new Node.js project, follow these steps:

  1. Open your terminal and run the following commands:
mkdir crud-api && cd crud-api
npm init -y

This creates a new folder named crud-api and initializes a Node.js project inside it.

  1. Install the required dependencies:
npm install express mongoose dotenv body-parser
  • express: A web framework for Node.js to help create APIs.
  • mongoose: A library to interact with MongoDB.
  • dotenv: Used for managing environment variables.
  • body-parser: Helps parse incoming JSON requests.

2. Create a Basic Express Server

Inside your project folder, create a new file called index.js and add the following code:

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

const app = express();
app.use(express.json()); // Middleware to parse JSON

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log("MongoDB Connected"))
    .catch(err => console.log(err));

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

Breaking Down the Code:

  1. Loading Environment Variables:

    • require('dotenv').config(); allows us to store sensitive data (like database credentials) in a .env file.
  2. Setting Up Express:

    • const app = express(); initializes an Express app.
    • app.use(express.json()); enables JSON parsing for incoming requests.
  3. Connecting to MongoDB:

    • mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) connects our API to MongoDB.
  4. Starting the Server:

    • app.listen(PORT, () => console.log("Server running")) runs our API on port 5000 or a specified environment port.

Now, when you run:

node index.js

Your API server should be running!


Defining a Mongoose Model

A model defines the structure of documents in a MongoDB collection. Let's create a model for books.

Create a new folder called models and inside it, create a file named Book.js.

const mongoose = require('mongoose');

const BookSchema = new mongoose.Schema({
    title: String,
    author: String,
    publishedYear: Number
});

module.exports = mongoose.model('Book', BookSchema);

Explanation:

  • mongoose.Schema defines a structure with title, author, and publishedYear fields.
  • mongoose.model('Book', BookSchema); creates a model named Book, which interacts with the books collection in MongoDB.

Creating CRUD Routes

Now, let's create the API routes to handle CRUD operations.

Create the Routes File

Inside a new routes folder, create a file named bookRoutes.js.

1. Create a Book (POST Request)

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

router.post('/', async (req, res) => {
    try {
        const book = new Book(req.body);
        await book.save();
        res.status(201).json(book);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

Explanation:

  • router.post('/') listens for a POST request at /api/books.
  • new Book(req.body) creates a new book from request data.
  • .save() stores the book in MongoDB.
  • res.status(201).json(book) returns the created book.

2. Get All Books (GET Request)

router.get('/', async (req, res) => {
    try {
        const books = await Book.find();
        res.status(200).json(books);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

Explanation:

  • Book.find() fetches all books from the database.
  • res.status(200).json(books); returns the list of books.

3. Get a Single Book by ID (GET Request)

router.get('/:id', async (req, res) => {
    try {
        const book = await Book.findById(req.params.id);
        if (!book) return res.status(404).json({ error: "Book not found" });
        res.json(book);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

Integrating Routes in index.js

Modify index.js to include the routes:

const bookRoutes = require('./routes/bookRoutes');
app.use('/api/books', bookRoutes);

Now, our API is fully functional!


Conclusion

CRUD operations are the foundation of API development. With Express and MongoDB, you can create structured, maintainable, and efficient APIs. Now that you've mastered basic CRUD, your next steps should be authentication, pagination, and performance optimization.

Happy coding! 🚀

Wrap-Up and Feedback 💬

Thank you for taking the time to read this article! I hope it helped simplify the topic for you and provided valuable insights. If you found it helpful, consider following me for more easy-to-digest content on web development and other tech topics.

Your feedback matters! Share your thoughts in the comments section—whether it's suggestions, questions, or areas you'd like me to improve. Feel free to use the reaction emojis to let me know how this article made you feel. 😊


Stay Connected 🌐

I’d love to connect with you! Let’s continue exchanging ideas, learning from each other, and growing together.

Follow me on my socials and let’s stay in touch:

Looking forward to hearing from you and growing this community of curious minds! 🚀