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
Create a main project folder, e.g.,
bookstore.Inside
bookstore, create amodelsfolder to house our Mongoose schemas and data interaction logic.Create an
app.jsfile directly in thebookstoreroot. This will be the main entry point for our application.
π package.json Initialization
The package.json file manages project metadata and dependencies.
Navigate to the
bookstoredirectory in your command line (e.g., using Git Bash:right-click > Git Bash Here).Run
npm initto create thepackage.jsonfile. You'll be prompted for information:Name:
bookstoreVersion: (default is fine)
Description:
Simple bookstore appEntry point:
app.jsAuthor: (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
Save the
package.jsonfile.In your command line, run
npm install. This command readspackage.jsonand installs all listed dependencies into anode_modulesfolder.
βοΈ 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 connectionIf the
bookstoredatabase 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 bodiesThis 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.
Install Nodemon globally:
npm install -g nodemonRun your application using Nodemon:
nodemon app.jsNow, 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
Navigate to your MongoDB installation's
bindirectory (e.g.,C:\Program Files\MongoDB\Server\3.0\bin).Open your command line (e.g., Windows Command Prompt as administrator) in this directory.
Run
mongoto open the MongoDB shell.
π Creating Database and Collections
Switch to/Create Database:
use bookstoreThis switches to the
bookstoredatabase. If it doesn't exist, MongoDB will create it.
Create Collections:
db.createCollection('books')db.createCollection('genres')
Verify Collections:
show collections(should showbooksandgenres)
β 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 requestUse
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 thename(String, required) andcreate_date(Date, defaults to current time).GenreModel: Created from the schema, this model is exported for use inapp.js.Methods:
getGenres,addGenre,updateGenre,deleteGenreare defined as static methods on the exported module for interacting with thegenrescollection.
π 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 liketitle,genre,description,author,publisher,pages,image_url,buy_url, andcreate_date.BookModel: Exported for use inapp.js.Methods:
getBooks,getBookById,addBook,updateBook,deleteBookare defined for thebookscollection.
πΊοΈ 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:
GETURL:
/api/genresFunctionality: 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:
POSTURL:
/api/genresFunctionality: 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:
PUTURL:
/api/genres/:_idFunctionality: 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:
DELETEURL:
/api/genres/:_idFunctionality: 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:
GETURL:
/api/booksFunctionality: 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:
GETURL:
/api/books/:_idFunctionality: 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:
POSTURL:
/api/booksFunctionality: 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:
PUTURL:
/api/books/:_idFunctionality: 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:
DELETEURL:
/api/books/:_idFunctionality: 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)
Install: Add the "Rest Easy" extension to Chrome.
Open: Launch the Rest Easy app.
Set URL:
http://localhost:3000/api/genres(or/api/books, etc.).Select Method: Choose
GET,POST,PUT, orDELETE.Headers (for POST/PUT): Add a header:
Key:
Content-TypeValue:
application/json
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" }
Send Request: Click "Send".
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.bodyinto 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.