You are currently viewing Building a RESTful API with Node.js and Mongoose

Building a RESTful API with Node.js and Mongoose

  • Post author:
  • Post category:Nodejs
  • Post comments:0 Comments
  • Post last modified:February 24, 2024

In this tutorial, we’ll create a simple RESTful API using Node.js and Mongoose, a MongoDB object modeling tool designed to work in an asynchronous environment. We’ll set up a basic Node.js server, define a schema using Mongoose, and create endpoints for CRUD operations (Create, Read, Update, Delete) on a “Todo” resource.

Prerequisites

  • Node.js installed on your machine
  • MongoDB installed locally or accessible remotely (you can also use a cloud MongoDB service like MongoDB Atlas)
  • Basic knowledge of JavaScript and RESTful APIs

Step 1: Initialize a Node.js Project

First, let’s create a new directory for our project and initialize a new Node.js project.

mkdir nodejs-mongoose-api
cd nodejs-mongoose-api
npm init -y

Step 2: Install Dependencies

We’ll need Express for our server, Mongoose for MongoDB object modeling, and Body-parser for handling request bodies.

npm install express mongoose body-parser

Step 3: Set Up the Server

Create a file named server.js and set up a basic Express server.

// server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
const PORT = 3000;

app.use(bodyParser.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/todo', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const Todo = mongoose.model('Todo', {
  title: String,
  description: String,
  done: Boolean,
});

// Routes
app.get('/api/todos', async (req, res) => {
  try {
    const todos = await Todo.find();
    res.json(todos);
  } catch (err) {
    res.status(500).send(err);
  }
});

app.post('/api/todos', async (req, res) => {
  const { title, description } = req.body;
  const todo = new Todo({
    title,
    description,
    done: false,
  });

  try {
    await todo.save();
    res.status(201).json(todo);
  } catch (err) {
    res.status(400).send(err);
  }
});

app.put('/api/todos/:id', async (req, res) => {
  const { id } = req.params;

  try {
    const todo = await Todo.findByIdAndUpdate(id, req.body, { new: true });
    if (!todo) {
      return res.status(404).send('Todo not found');
    }
    res.json(todo);
  } catch (err) {
    res.status(400).send(err);
  }
});

app.delete('/api/todos/:id', async (req, res) => {
  const { id } = req.params;

  try {
    const todo = await Todo.findByIdAndDelete(id);
    if (!todo) {
      return res.status(404).send('Todo not found');
    }
    res.json(todo);
  } catch (err) {
    res.status(400).send(err);
  }
});

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

Step 4: Run the Server

Now let’s run our Node.js server.

node server.js

Your server should now be running on http://localhost:3000.

Step 5: Test the API Endpoints

You can use tools like Postman or curl to test the API endpoints.

GET /api/todos

curl http://localhost:3000/api/todos

POST /api/todos

curl -X POST -H "Content-Type: application/json" -d '{"title": "Do laundry", "description": "Wash clothes"}' http://localhost:3000/api/todos

PUT /api/todos/:id

Replace :id with the ID of an existing todo.

curl -X PUT -H "Content-Type: application/json" -d '{"done": true}' http://localhost:3000/api/todos/1

DELETE /api/todos/:id

Replace :id with the ID of an existing todo.

curl -X DELETE http://localhost:3000/api/todos/1

Conclusion

This API allows you to perform CRUD operations on a “Todo” resource. This is just a starting point, and you can expand upon this by adding more routes, validations, error handling, and authentication as needed for your application.

Leave a Reply