1. Home
  2. Explore
  3. Computer Science
  4. Node.js Express API

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Node.js Express API

πŸš€ Building a RESTful Web API with Node.js & Express

This guide details how to construct a RESTful web API service using Node.js and Express. The focus is entirely on the backend service, enabling the application to handle GET, POST, PUT, and DELETE requests for data. We will build this service from scratch, emphasizing a deep understanding of each component rather than relying on scaffolding tools.


πŸ› οΈ Core Technologies & Setup

We leverage several powerful technologies to build our API:

🌐 Node.js

  • Description: Node.js allows us to run JavaScript on the server side. It utilizes the same JavaScript engine as Google Chrome, making it very efficient.

  • Installation:

    • Windows: Download and run the installer from the official Node.js website.

    • Linux: Use your preferred package manager (e.g., apt, yum).

  • Included Tools: Installing Node.js also installs npm (Node Package Manager), which is crucial for managing project dependencies.

⚑ Express

  • Description: Express is a minimalist web framework for Node.js. It provides robust features for web and mobile applications, including a web server to handle HTTP requests and support for template engines.

  • Installation: Installed via npm (e.g., npm install express). We will install it locally for the project.

πŸ—„οΈ MongoDB

  • Description: MongoDB is a NoSQL document database used as our data store. It stores data in flexible, JSON-like documents.

  • Installation: Similar to Node.js, download and run the installer for your operating system.

  • Client: MongoDB comes with a command-line client (mongo) for interacting with the database.

πŸ“¦ Mongoose

  • Description: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward, schema-based solution to model your application data, enforcing structure and facilitating interactions with MongoDB.

  • Installation: Installed via npm (e.g., npm install mongoose).

πŸ’» Command Line Tool

  • Recommendation: While standard Windows Command Prompt or PowerShell works, Git Bash (included with Git for Windows) is often preferred for its Unix-like command-line interface.


πŸ“‚ Project Structure & Initialization

We'll set up our project with a clear directory structure and initialize it using npm.

πŸ“ Initial Folder Setup

  1. Create a main project folder, e.g., bookstore.

  2. Inside bookstore, create a models folder to house our Mongoose schemas and data interaction logic.

  3. Create an app.js file directly in the bookstore root. This will be the main entry point for our application.

πŸ“ package.json Initialization

The package.json file manages project metadata and dependencies.

  1. Navigate to the bookstore directory in your command line (e.g., using Git Bash: right-click > Git Bash Here).

  2. Run npm init to create the package.json file. You'll be prompted for information:

    • Name: bookstore

    • Version: (default is fine)

    • Description: Simple bookstore app

    • Entry point: app.js

    • Author: (your name)

    • License: (default is fine)

    • Confirm the generated structure.

βž• Adding Dependencies

After npm init, open package.json in your text editor. We need to manually add our dependencies:

{
  "name": "bookstore",
  "version": "1.0.0",
  "description": "Simple bookstore app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Your Name",
  "license": "ISC",
  "dependencies": {
    "express": "*",
    "body-parser": "*",
    "mongoose": "*"
  }
}
  • "express": "*": Specifies Express as a dependency, * means the latest version.

  • "body-parser": "*": Essential middleware for parsing incoming request bodies (e.g., JSON, URL-encoded data).

  • "mongoose": "*": Our ODM for MongoDB.

πŸ“¦ Installing Dependencies

  1. Save the package.json file.

  2. In your command line, run npm install. This command reads package.json and installs all listed dependencies into a node_modules folder.


βš™οΈ Application Setup (app.js)

The app.js file is where we configure our Express application, connect to MongoDB, and define our API routes.

πŸ“₯ Requiring Modules

At the top of app.js, we import the necessary modules:

var express = require('express');
var app = express(); // Initialize Express application
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

πŸ“‘ Connecting to MongoDB

We establish a connection to our MongoDB database using Mongoose.

mongoose.connect('mongodb://localhost/bookstore'); // Connect to 'bookstore' database
var db = mongoose.connection; // Get the default connection
  • If the bookstore database doesn't exist, MongoDB will create it upon the first data insertion.

πŸ”„ Body-Parser Middleware

For handling POST and PUT requests with JSON data, we need to use body-parser middleware:

app.use(bodyParser.json()); // Enable parsing of JSON request bodies
  • This line should be placed before any routes that handle POST/PUT requests.

πŸš€ Starting the Server

The application needs to listen on a specific port:

app.listen(3000); // Listen for requests on port 3000
console.log('Running on Port 3000...');

πŸ”„ Auto-Restart with Nodemon

To avoid manually restarting the Node.js application after every code change, we can use Nodemon.

  1. Install Nodemon globally: npm install -g nodemon

  2. Run your application using Nodemon: nodemon app.js

    • Now, any changes saved to app.js (or other watched files) will automatically restart the server.


πŸ—„οΈ Database Setup & Initial Data (MongoDB Shell)

Before defining API routes, we need to create our collections and add some initial data.

🐚 Accessing MongoDB Shell

  1. Navigate to your MongoDB installation's bin directory (e.g., C:\Program Files\MongoDB\Server\3.0\bin).

  2. Open your command line (e.g., Windows Command Prompt as administrator) in this directory.

  3. Run mongo to open the MongoDB shell.

πŸ“š Creating Database and Collections

  1. Switch to/Create Database: use bookstore

    • This switches to the bookstore database. If it doesn't exist, MongoDB will create it.

  2. Create Collections:

    • db.createCollection('books')

    • db.createCollection('genres')

  3. Verify Collections: show collections (should show books and genres)

βž• Inserting Sample Data

We'll insert some sample genres and books.

Genres:

db.genres.insert({ name: 'Suspense' });
db.genres.insert({ name: 'Self-Help' });
db.genres.insert({ name: 'Romance' }); // Added later via POST request
  • Use db.genres.find().pretty() to view inserted genres.

Books:

db.books.insert({
    title: 'The Murder House',
    genre: 'Suspense',
    description: 'A thrilling mystery novel...',
    author: 'James Patterson',
    publisher: 'Little, Brown and Company',
    pages: 480,
    image_url: 'http://example.com/murder-house.jpg',
    buy_url: 'http://barnesandnoble.com/murder-house'
});

db.books.insert({
    title: 'Truth Or Die',
    genre: 'Suspense',
    description: 'Another gripping tale...',
    author: 'James Patterson',
    publisher: 'Little, Brown and Company',
    pages: 400,
    image_url: 'http://example.com/truth-or-die.jpg',
    buy_url: 'http://barnesandnoble.com/truth-or-die'
});
  • Use db.books.find().pretty() to view inserted books.


πŸ“– Mongoose Models & Schemas

Mongoose models define the structure of our data and encapsulate database interaction logic.

πŸ“ models/genre.js

var mongoose = require('mongoose');

// Genre Schema
var genreSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    create_date: {
        type: Date,
        default: Date.now
    }
});

var Genre = module.exports = mongoose.model('Genre', genreSchema);

// Get Genres
module.exports.getGenres = function(callback, limit) {
    Genre.find(callback).limit(limit);
}

// Add Genre
module.exports.addGenre = function(genre, callback) {
    Genre.create(genre, callback);
}

// Update Genre
module.exports.updateGenre = function(id, genre, options, callback) {
    var query = { _id: id };
    var update = {
        name: genre.name
    };
    Genre.findOneAndUpdate(query, update, options, callback);
}

// Delete Genre
module.exports.deleteGenre = function(id, callback) {
    var query = { _id: id };
    Genre.remove(query, callback);
}
  • genreSchema: Defines the name (String, required) and create_date (Date, defaults to current time).

  • Genre Model: Created from the schema, this model is exported for use in app.js.

  • Methods: getGenres, addGenre, updateGenre, deleteGenre are defined as static methods on the exported module for interacting with the genres collection.

πŸ“š models/book.js

var mongoose = require('mongoose');

// Book Schema
var bookSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    genre: {
        type: String,
        required: true
    },
    description: {
        type: String
    },
    author: {
        type: String
    },
    publisher: {
        type: String
    },
    pages: {
        type: String // or Number
    },
    image_url: {
        type: String
    },
    buy_url: {
        type: String
    },
    create_date: {
        type: Date,
        default: Date.now
    }
});

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

// Get Books
module.exports.getBooks = function(callback, limit) {
    Book.find(callback).limit(limit);
}

// Get Book by ID
module.exports.getBookById = function(id, callback) {
    Book.findById(id, callback);
}

// Add Book
module.exports.addBook = function(book, callback) {
    Book.create(book, callback);
}

// Update Book
module.exports.updateBook = function(id, book, options, callback) {
    var query = { _id: id };
    var update = {
        title: book.title,
        genre: book.genre,
        description: book.description,
        author: book.author,
        publisher: book.publisher,
        pages: book.pages,
        image_url: book.image_url,
        buy_url: book.buy_url
    };
    Book.findOneAndUpdate(query, update, options, callback);
}

// Delete Book
module.exports.deleteBook = function(id, callback) {
    var query = { _id: id };
    Book.remove(query, callback);
}
  • bookSchema: Defines fields like title, genre, description, author, publisher, pages, image_url, buy_url, and create_date.

  • Book Model: Exported for use in app.js.

  • Methods: getBooks, getBookById, addBook, updateBook, deleteBook are defined for the books collection.


πŸ—ΊοΈ API Routes (app.js)

Here we define the RESTful endpoints that our API will expose, linking them to the Mongoose model methods.

πŸ”— Requiring Models

First, we need to import our Mongoose models into app.js:

var Genre = require('./models/genre'); // Capital G for the model object
var Book = require('./models/book');   // Capital B for the model object

🏠 Root Endpoint

A simple message for the root URL, guiding users to the API endpoints.

app.get('/', function(req, res) {
    res.send('Please use /api/books or /api/genres');
});

🏷️ Genre Endpoints

➑️ GET All Genres

  • Method: GET

  • URL: /api/genres

  • Functionality: Retrieves all genres from the database.

app.get('/api/genres', function(req, res) {
    Genre.getGenres(function(err, genres) {
        if (err) {
            throw err;
        }
        res.json(genres); // Send genres as JSON response
    });
});

βž• POST Add Genre

  • Method: POST

  • URL: /api/genres

  • Functionality: Adds a new genre to the database based on the request body.

app.post('/api/genres', function(req, res) {
    var genre = req.body; // Genre data from the request body
    Genre.addGenre(genre, function(err, genre) {
        if (err) {
            throw err;
        }
        res.json(genre); // Respond with the newly added genre
    });
});

✍️ PUT Update Genre

  • Method: PUT

  • URL: /api/genres/:_id

  • Functionality: Updates an existing genre by its ID.

app.put('/api/genres/:_id', function(req, res) {
    var id = req.params._id; // Get ID from URL parameters
    var genre = req.body;    // New genre data from the request body
    Genre.updateGenre(id, genre, {}, function(err, genre) {
        if (err) {
            throw err;
        }
        res.json(genre); // Respond with the updated genre
    });
});

πŸ—‘οΈ DELETE Genre

  • Method: DELETE

  • URL: /api/genres/:_id

  • Functionality: Deletes a genre by its ID.

app.delete('/api/genres/:_id', function(req, res) {
    var id = req.params._id; // Get ID from URL parameters
    Genre.deleteGenre(id, function(err, genre) {
        if (err) {
            throw err;
        }
        res.json(genre); // Respond with confirmation (or the deleted object)
    });
});

πŸ“– Book Endpoints

➑️ GET All Books

  • Method: GET

  • URL: /api/books

  • Functionality: Retrieves all books from the database.

app.get('/api/books', function(req, res) {
    Book.getBooks(function(err, books) {
        if (err) {
            throw err;
        }
        res.json(books);
    });
});

πŸ”Ž GET Single Book by ID

  • Method: GET

  • URL: /api/books/:_id

  • Functionality: Retrieves a single book by its ID.

app.get('/api/books/:_id', function(req, res) {
    Book.getBookById(req.params._id, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    });
});

βž• POST Add Book

  • Method: POST

  • URL: /api/books

  • Functionality: Adds a new book to the database.

app.post('/api/books', function(req, res) {
    var book = req.body;
    Book.addBook(book, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    });
});

✍️ PUT Update Book

  • Method: PUT

  • URL: /api/books/:_id

  • Functionality: Updates an existing book by its ID.

app.put('/api/books/:_id', function(req, res) {
    var id = req.params._id;
    var book = req.body;
    Book.updateBook(id, book, {}, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    });
});

πŸ—‘οΈ DELETE Book

  • Method: DELETE

  • URL: /api/books/:_id

  • Functionality: Deletes a book by its ID.

app.delete('/api/books/:_id', function(req, res) {
    var id = req.params._id;
    Book.deleteBook(id, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    });
});

πŸ§ͺ Testing the API

To test the API, you can use tools like Rest Easy (a Chrome extension) or Postman.

🌐 Using Rest Easy (or similar HTTP Client)

  1. Install: Add the "Rest Easy" extension to Chrome.

  2. Open: Launch the Rest Easy app.

  3. Set URL: http://localhost:3000/api/genres (or /api/books, etc.).

  4. Select Method: Choose GET, POST, PUT, or DELETE.

  5. Headers (for POST/PUT): Add a header:

    • Key: Content-Type

    • Value: application/json

  6. Body (for POST/PUT): Provide a JSON object for the data to be sent.

    • Example (POST /api/genres):

    • Example (PUT /api/genres/:id):

      {
          "name": "Thriller"
      }
  7. Send Request: Click "Send".

  8. Verify: Check the response from the API and confirm changes in the MongoDB shell (db.genres.find().pretty(), db.books.find().pretty()).


πŸ”’ Security Considerations (Production Apps)

This tutorial focuses on core API functionality. For production applications, additional security measures are crucial:

  • Input Validation: Thoroughly validate all incoming data to prevent malicious input and ensure data integrity.

  • Authentication/Authorization: Implement mechanisms to verify user identity and control access to resources.

  • Field Dissection: Instead of directly inserting req.body into the database, explicitly pick and assign fields to prevent unexpected data insertion.

  • Error Handling: Implement robust error handling for all API endpoints.

This comprehensive guide provides a solid foundation for building RESTful APIs with Node.js, Express, and MongoDB.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent