0% found this document useful (0 votes)
8 views31 pages

Developing RESTful APIs with Node.js

The document provides lecture notes on developing RESTful APIs using Node.js and Express, covering topics such as RESTful API principles, CRUD operations, and setting up a server. It includes practical examples for creating routes, handling HTTP requests, and integrating MongoDB. Best practices for API development and common HTTP status codes are also discussed to enhance reliability and maintainability.

Uploaded by

imzdx003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views31 pages

Developing RESTful APIs with Node.js

The document provides lecture notes on developing RESTful APIs using Node.js and Express, covering topics such as RESTful API principles, CRUD operations, and setting up a server. It includes practical examples for creating routes, handling HTTP requests, and integrating MongoDB. Best practices for API development and common HTTP status codes are also discussed to enhance reliability and maintainability.

Uploaded by

imzdx003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

VIVEKANANDA GLOBAL UNIVERSITY

DEPARTMENT OF COMPUTER SCIENCE AND APPLICATIONS

LECTURE NOTES
MODERN WEB APPLICATIONS
UGCSA301

MODULE – 3

Name of the Developing RESTful APIs with


Module [Link] and Express
• Introduction to RESTful APIs and CRUD
operations
• Setting up a [Link] server with Express
• Creating routes and handling HTTP requests in
Express
Module Content • Implementing middleware for request
processing and error handling
• Integrating MongoDB as the database using
Mongoose ORM
• Project: Building a RESTful API backend for the
web application developed in Module 2

Name of HOD Mr. RAKESH SHARMA

Name of Lecturer Mr. NITIN MATHEW VARGHESE


INTRODUCTION TO RESTFUL APIS AND CRUD OPERATIONS

1. Introduction to RESTful APIs


1.1 What is an API?
• API (Application Programming Interface):
A set of rules and protocols that allow software applications to communicate with
each other.
• APIs enable data exchange and functionality sharing between different systems or
components.
1.2 Web APIs
• Web APIs allow communication over the internet using HTTP/HTTPS protocols.
• They can be consumed by web apps, mobile apps, IoT devices, etc.
1.3 REST and RESTful APIs
• REST (Representational State Transfer):
An architectural style for designing networked applications introduced by Roy
Fielding in 2000.
• RESTful APIs follow REST principles to enable stateless client-server communication.
Key Characteristics of REST:
Feature Description
Client and server are independent; server provides
Client-Server
resources, client manages UI.
Each request from client contains all necessary
Stateless
information; server does not store session state.
Responses must define whether they are cacheable to
Cacheable
improve performance.
Standard way to interact with resources (URIs, HTTP
Uniform Interface
methods, JSON/XML).
APIs can be composed of multiple layers (load balancer,
Layered System
caching, etc.).
Code on Demand Servers can extend client functionality by transferring
(Optional) executable code.

1.4 RESTful API Basics


• Resources are identified by URIs (Uniform Resource Identifiers).
• Each resource can be manipulated using standard HTTP methods.
• Common data formats: JSON (preferred), XML, or others.
• Example:
o URI: /api/products/1
o HTTP Method: GET
o Response: JSON object representing product with ID 1.
2. CRUD Operations in RESTful APIs
CRUD = Create, Read, Update, Delete
These are the four basic functions for persistent storage.
CRUD HTTP
URI Example Description
Operation Method
Create POST /api/products Add a new resource.
Read /api/products or Fetch a list of resources or a
GET
(Retrieve) /api/products/{id} single resource.
Modify an existing resource.
PUT or PUT replaces the whole
Update /api/products/{id}
PATCH resource, PATCH partially
updates it.
Delete DELETE /api/products/{id} Remove a resource.
Typical RESTful API Workflow
1. Client sends an HTTP request to the server (with URL, method, headers, and body).
2. Server processes the request, interacts with a database, and performs business logic.
3. Server sends back an HTTP response (with status code and data).

3. Using [Link] and Express to Build RESTful APIs


3.1 Why [Link]?
• JavaScript runtime built on V8 engine.
• Handles asynchronous I/O effectively, making it great for scalable web APIs.
• Uses single-threaded event loop.
3.2 Why [Link]?
• Minimal and flexible [Link] web framework.
• Simplifies routing, request handling, middleware integration.
• Provides a clean structure for building APIs.
3.3 Basic Steps to Create a RESTful API
1. Install [Link]
Download and install from [Link]
2. Create a New Project
mkdir myapi
cd myapi
npm init -y
npm install express
3. Set up Express Server
// [Link]
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON
[Link]([Link]());
[Link](PORT, () => {
[Link](`Server running on [Link]
});
4. Define Routes for CRUD Operations
Example: Managing “Products”
let products = [
{ id: 1, name: 'Laptop', price: 60000 },
{ id: 2, name: 'Phone', price: 20000 }
];
// CREATE (POST)
[Link]('/api/products', (req, res) => {
const newProduct = [Link];
[Link](newProduct);
[Link](201).json(newProduct);
});
// READ (GET all)
[Link]('/api/products', (req, res) => {
[Link](products);
});
// READ (GET one)
[Link]('/api/products/:id', (req, res) => {
const product = [Link](p => [Link] == [Link]);
product ? [Link](product) : [Link](404).send('Not Found');
});
// UPDATE (PUT)
[Link]('/api/products/:id', (req, res) => {
const index = [Link](p => [Link] == [Link]);
if (index !== -1) {
products[index] = [Link];
[Link](products[index]);
} else {
[Link](404).send('Not Found');
}
});
// DELETE
[Link]('/api/products/:id', (req, res) => {
products = [Link](p => [Link] != [Link]);
[Link](204).send();
});
5. Test API Using Postman or Curl
o GET /api/products → Returns list of products.
o POST /api/products with JSON body → Creates a new product.
o PUT /api/products/:id → Updates existing product.
o DELETE /api/products/:id → Deletes product.

4. HTTP Status Codes in RESTful APIs


Code Meaning
200 OK Request successful.
201 Created New resource successfully created.
204 No Content Resource deleted or no response body.
400 Bad Request Invalid client request.
404 Not Found Resource does not exist.
500 Internal Server Error Server-side error.

5. Best Practices for RESTful API Development


• Use plural nouns for resource names (/api/users instead of /api/user).
• Keep URIs predictable and consistent.
• Return proper HTTP status codes.
• Use middleware for logging, authentication, and error handling.
• Support pagination, filtering, and sorting for large datasets.
• Implement authentication (JWT, OAuth2) for secure endpoints.

6. Summary
• RESTful APIs are a standardized way to build web services that are stateless,
scalable, and easy to consume.
• CRUD operations map directly to HTTP methods (POST, GET, PUT/PATCH, DELETE).
• [Link] and [Link] together provide a fast, simple, and powerful way to build
RESTful APIs.
• Proper status codes, naming conventions, and middleware improve reliability and
maintainability.
SETTING UP A [Link] SERVER WITH EXPRESS

1. Introduction
Modern web applications often need a backend server to handle data, manage business
logic, and communicate with databases and clients.
[Link] and [Link] together provide a powerful, lightweight, and efficient platform
for building such servers.
1.1 What is [Link]?
• [Link] is a JavaScript runtime environment built on the Google Chrome V8 engine.
• It allows developers to run JavaScript outside the browser, typically on the server
side.
• It uses an event-driven, non-blocking I/O model, making it efficient and scalable for
real-time applications.
Key Features of [Link]
Feature Description
Asynchronous & Non- Handles multiple requests without waiting for previous
blocking ones to complete.
Single Threaded Event Uses one main thread with event-driven architecture to
Loop manage concurrency.
Built on Google’s V8 engine, known for high
Fast Execution
performance.
NPM (Node Package
Provides thousands of reusable modules and libraries.
Manager)
Cross-platform Works on Windows, macOS, and Linux.

1.2 What is [Link]?


• [Link] is a minimal and flexible [Link] framework for building web servers and
APIs.
• It simplifies routing, middleware handling, and HTTP request management.
• Provides tools for handling GET, POST, PUT, DELETE requests easily.
Key Benefits of Express
• Simplifies HTTP request handling.
• Supports middleware for request pre-processing.
• Helps in routing different endpoints.
• Easy to integrate with databases (MongoDB, MySQL, etc.).
• Ideal for building RESTful APIs and web applications.

2. Setting Up a [Link] Server


Step 1: Install [Link]
• Download from [Link]
• Verify installation:
• node -v
• npm -v
o node -v → checks [Link] version.
o npm -v → checks Node Package Manager version.
3. Creating a Basic [Link] Server (Without Express)
Before using Express, it’s helpful to understand how Node’s built-in http module works.
Example: Basic HTTP Server
// [Link]
const http = require('http');
// Create server
const server = [Link]((req, res) => {
[Link] = 200;
[Link]('Content-Type', 'text/plain');
[Link]('Hello from [Link] server!');
});
// Server listens on port 3000
[Link](3000, () => {
[Link]('Server running at [Link]
});
Explanation
• [Link]() creates an HTTP server instance.
• req (request) and res (response) represent the HTTP objects.
• [Link]() binds the server to a port (e.g., 3000).
• To run:
• node [Link]
• Visit [Link] in your browser.

4. Setting Up a [Link] Server Using Express


Express simplifies the server creation process and adds routing & middleware features.
Step 1: Initialize a New Project
mkdir express-server
cd express-server
npm init -y
• npm init -y creates a default [Link] file.
Step 2: Install Express
npm install express
Step 3: Create Server File
// [Link]
const express = require('express');
const app = express();
// Define a port
const PORT = 3000;
// Basic route
[Link]('/', (req, res) => {
[Link]('Welcome to Express Server!');
});
// Start server
[Link](PORT, () => {
[Link](`Server running on [Link]
});
Step 4: Run the Server
node [Link]
• Open browser → [Link]
• Output → Welcome to Express Server!

5. Handling Routes in Express


Express allows defining routes for different endpoints and HTTP methods.
Example: Multiple Routes
[Link]('/', (req, res) => {
[Link]('Home Page');
});
[Link]('/about', (req, res) => {
[Link]('About Page');
});
[Link]('/contact', (req, res) => {
[Link]('Contact Form Submitted');
});
Common HTTP Methods
Method Description
GET Retrieve data from server
POST Send data to server
PUT/PATCH Update existing data
DELETE Remove data

6. Using Middleware in Express


What is Middleware?
• Middleware functions are executed between the request and response cycle.
• They can modify requests, perform authentication, or log activity.
Example: Using Middleware
// Built-in middleware for JSON parsing
[Link]([Link]());
// Custom middleware
[Link]((req, res, next) => {
[Link](`${[Link]} ${[Link]}`);
next(); // passes control to the next handler
});
[Link]('/', (req, res) => {
[Link]('Middleware Example');
});
Types of Middleware
Type Description
Application-level Applied globally (e.g., [Link]()).
Router-level Applied to specific routers or routes.
Built-in Middleware Provided by Express ([Link](), [Link]()).
Third-party Middleware Installed from npm (e.g., morgan, cors).

7. Serving Static Files


You can serve HTML, CSS, images, or JS files using Express’s static middleware.
Example
[Link]([Link]('public'));
• Place your files in a folder named public/.
• Example: public/[Link] accessible at [Link]

8. Handling JSON Data


Modern APIs often send and receive data in JSON format.
Example: POST Request Handling
[Link]([Link]()); // Parse JSON body
[Link]('/api/data', (req, res) => {
const userData = [Link];
[Link](userData);
[Link](201).send(`Data received for ${[Link]}`);
});
Use Postman or curl to test POST requests:
curl -X POST -H "Content-Type: application/json" \
-d '{"name":"John"}' [Link]

9. Common HTTP Status Codes


Code Meaning
200 OK Successful request
201 Created Resource created successfully
400 Bad Request Invalid client request
404 Not Found Requested resource not found
500 Internal Server Error Server-side error

10. Example: Simple Express API


const express = require('express');
const app = express();
[Link]([Link]());
let users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// GET all users
[Link]('/api/users', (req, res) => [Link](users));
// GET user by ID
[Link]('/api/users/:id', (req, res) => {
const user = [Link](u => [Link] == [Link]);
user ? [Link](user) : [Link](404).send('User Not Found');
});
// POST new user
[Link]('/api/users', (req, res) => {
const newUser = [Link];
[Link](newUser);
[Link](201).json(newUser);
});
[Link](3000, () => [Link]('Server running on port 3000'));

11. Summary
Concept Description
[Link] Server-side JavaScript runtime environment.
[Link] Framework that simplifies [Link] web development.
Routing Defines how server responds to various requests.
Middleware Functions that handle requests before the final response.
Static Serving Used to serve HTML, CSS, JS, and other static files.
JSON Handling Enables RESTful API interactions.

12. Real-world Applications of [Link] + Express


• Building RESTful APIs for web and mobile applications.
• Developing real-time applications (chat apps, notifications).
• Serving single-page applications (React, Angular, Vue).
• Connecting databases like MongoDB, MySQL, or PostgreSQL.
CREATING ROUTES AND HANDLING HTTP REQUESTS IN EXPRESS

1. Introduction to Routing in Express


1.1 What is Routing?
• Routing refers to how an application’s endpoints (URIs) respond to client requests.
• In simple terms, routing defines how the server handles different URL paths and
HTTP methods.
For example,
• /home may show a homepage.
• /users may display a list of users.
• /products/:id may show details of a specific product.
In Express, routing helps in directing incoming HTTP requests to the appropriate logic
or controller based on the request’s path and method.

2. Basic Routing Structure in Express


2.1 Syntax
[Link](PATH, HANDLER)
Term Description
app Instance of the Express application.
METHOD HTTP request method (GET, POST, PUT, DELETE, etc.).
PATH URL path (route) on the server.
HANDLER Function executed when the route is matched (callback).
2.2 Example: Basic Route
const express = require('express');
const app = express();

[Link]('/', (req, res) => {


[Link]('Welcome to the Home Page');
});
[Link](3000, () => [Link]('Server running on port 3000'));
Explanation:
• When a client sends a GET request to /, the server responds with "Welcome to the
Home Page".
• The [Link]() function sends an HTTP response to the client.

3. HTTP Methods in Express


Express supports all standard HTTP request methods. Each method is used for a specific
purpose in RESTful APIs.
HTTP Method Description Typical Use
GET Retrieve data from the server Fetch list or a specific record
POST Send data to the server Create new data or record
PUT Replace existing data Update complete data
PATCH Modify part of an existing record Partial update
DELETE Remove data Delete a record
4. Examples of Routes with HTTP Methods
4.1 GET Route
[Link]('/users', (req, res) => {
[Link]('Fetching all users...');
});
• Used to retrieve data from the server.
• Example: Fetching a list of users from a database.

4.2 POST Route


[Link]('/users', (req, res) => {
[Link]('Creating a new user...');
});
• Used to send or create new data on the server.
• Usually, client sends data in JSON format via request body.

4.3 PUT Route


[Link]('/users/:id', (req, res) => {
[Link](`Updating user with ID ${[Link]}`);
});
• Used to update an existing record entirely.

4.4 PATCH Route


[Link]('/users/:id', (req, res) => {
[Link](`Partially updating user with ID ${[Link]}`);
});
• Used for partial updates to a resource.

4.5 DELETE Route


[Link]('/users/:id', (req, res) => {
[Link](`Deleting user with ID ${[Link]}`);
});
• Used to delete data from the server.

5. Accessing Request and Response Objects


Express provides two important objects inside each route handler:

Object Description
Represents the HTTP request, contains data sent by the
req (Request)
client (URL, headers, body, etc.).
Represents the HTTP response, used to send data back to
res (Response)
the client.
Common req Properties
Property Description Example
[Link] Parameters from URL path /users/:id → [Link]
/users?name=John →
[Link] Query string parameters
[Link]
Data sent in POST/PUT
[Link] { "name": "John" }
requests
[Link] HTTP method used GET, POST, etc.
[Link] Requested URL /users/1
Common res Methods
Method Description Example
[Link]() Send a string or object response [Link]('Hello')
[Link]() Send a JSON response [Link]({ name: 'John' })
[Link](404).send('Not
[Link]() Set HTTP status code
Found')
[Link]() Redirect to another route [Link]('/home')

6. Route Parameters and Query Strings


6.1 Route Parameters
Used to capture dynamic values from the URL path.
[Link]('/users/:id', (req, res) => {
[Link](`User ID: ${[Link]}`);
});
Example:
• URL: /users/10
• Output: User ID: 10

6.2 Query Parameters


Used to send optional parameters after a question mark (?) in the URL.
[Link]('/search', (req, res) => {
[Link](`Search term: ${[Link].q}`);
});
Example:
• URL: /search?q=apple
• Output: Search term: apple

7. Handling JSON Data in Routes


To handle JSON data in POST or PUT requests, enable Express’s JSON parser middleware.
[Link]([Link]());
[Link]('/users', (req, res) => {
[Link]([Link]); // Access the data sent by client
[Link](201).send('User Created');
});
Example request (using Postman or curl):
{
"name": "Alice",
"age": 25
}

8. Grouping Routes with Router


When building larger applications, you can organize routes using Express Router.
8.1 Creating a Router File
[Link]
const express = require('express');
const router = [Link]();
[Link]('/', (req, res) => [Link]('All Users'));
[Link]('/', (req, res) => [Link]('Add User'));
[Link]('/:id', (req, res) => [Link](`User ID: ${[Link]}`));
[Link] = router;

8.2 Importing Router in Main App


[Link]
const express = require('express');
const app = express();
const userRoutes = require('./userRoutes');
[Link]('/users', userRoutes);
[Link](3000, () => [Link]('Server running on port 3000'));
Now:
• /users → All Users
• /users/1 → User ID: 1

9. Handling 404 and Errors


9.1 404 (Not Found) Route
[Link]((req, res) => {
[Link](404).send('404 - Page Not Found');
});
9.2 Global Error Handling Middleware
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).send('Something broke!');
});

10. Example: Complete Routing Application


const express = require('express');
const app = express();
[Link]([Link]());
// GET all users
[Link]('/users', (req, res) => [Link]([{ id: 1, name: 'Alice' }]));
// GET user by ID
[Link]('/users/:id', (req, res) => [Link](`User ID: ${[Link]}`));
// POST create user
[Link]('/users', (req, res) => {
const user = [Link];
[Link](201).json({ message: 'User created', user });
});

// PUT update user


[Link]('/users/:id', (req, res) => [Link](`Updated user ${[Link]}`));

// DELETE user
[Link]('/users/:id', (req, res) => [Link](`Deleted user ${[Link]}`));

// 404 handler
[Link]((req, res) => [Link](404).send('Route not found'));

[Link](3000, () => [Link]('Server running on port 3000'));

11. Best Practices for Routing


• Use plural nouns for route names (e.g., /users, /products).
• Separate routes into different files using Express Router.
• Use appropriate HTTP status codes.
• Implement error handling and input validation.
• Follow RESTful conventions for clarity and consistency.

12. Summary
Concept Description
Routing Defines how server responds to various HTTP requests.
HTTP Methods Used for CRUD operations (GET, POST, PUT, DELETE).
Route Parameters Capture dynamic values from URLs.
Query Parameters Send optional filters or parameters.
Express Router Helps modularize routes for better structure.
IMPLEMENTING MIDDLEWARE FOR REQUEST PROCESSING AND ERROR HANDLING

1. Introduction
1.1 What is Middleware?
• Middleware refers to functions that execute during the request-response cycle in
an Express application.
• They act as a bridge between the incoming request (client) and the final response
(server).
• Each middleware function can:
o Execute code
o Modify the request (req) or response (res) objects
o End the request-response cycle
o Call the next middleware function in the stack using next()
1.2 Importance of Middleware
Middleware helps to:
• Process or transform incoming requests (e.g., parsing JSON, validating input).
• Implement security (authentication, authorization).
• Handle errors gracefully.
• Manage logging, session management, and CORS (Cross-Origin Resource Sharing).
• Make the application modular and maintainable.

2. The Express Middleware Concept


2.1 Middleware Flow
When a request is made to the server:
1. It enters the Express middleware pipeline.
2. Each middleware function runs in order.
3. Each can either:
o Pass control to the next middleware (next()), or
o End the response using [Link]() or similar methods.
Middleware Chain Example:
Request → Middleware 1 → Middleware 2 → Route Handler → Response

3. Syntax of Middleware Function


[Link]((req, res, next) => {
// Code to process the request
[Link]('Middleware executed');
next(); // Pass control to next middleware
});
Parameter Description
req HTTP Request object
res HTTP Response object
next Function to call the next middleware or route handler
4. Types of Middleware in Express
Type Description Example
Application- Applied globally using
Logging, JSON parsing
level [Link]()
Applied to specific routes
Router-level Middleware specific to a route
using [Link]()
Provided by Express
Built-in [Link](), [Link]()
framework
Third-party Installed via npm morgan, cors, helmet
Handles runtime or request Custom middleware with 4
Error-handling
errors parameters (err, req, res, next)

5. Application-Level Middleware
Example 1: Logging Middleware
const express = require('express');
const app = express();

[Link]((req, res, next) => {


[Link](`${[Link]} ${[Link]} - ${new Date()}`);
next();
});

[Link]('/', (req, res) => [Link]('Home Page'));

[Link](3000, () => [Link]('Server running on port 3000'));


Explanation:
• Logs every request with its method, URL, and timestamp.
• Calls next() to pass control to the next handler.

6. Built-in Middleware
Express provides some commonly used built-in middleware functions:
Middleware Description Usage
Parses incoming requests
[Link]() [Link]([Link]());
with JSON payloads
[Link] Parses URL-encoded form [Link]([Link]({
() data extended: true }));
Serves static files (HTML,
[Link]() [Link]([Link]('public'));
CSS, JS, images)
Example:
[Link]([Link]());
[Link]([Link]('public'));
7. Router-Level Middleware
Router-level middleware works just like application-level middleware but is applied to
specific route groups using an Express Router.
Example:
const express = require('express');
const app = express();
const router = [Link]();
[Link]((req, res, next) => {
[Link]('Router-specific middleware executed');
next();
});
[Link]('/users', (req, res) => [Link]('User List'));
[Link]('/api', router);
[Link](3000, () => [Link]('Server running on port 3000'));
Explanation:
• Middleware is applied only to routes starting with /api.
• /api/users → executes router-level middleware.
• / → does not execute it.

8. Third-Party Middleware
Third-party middleware modules are installed from npm and extend Express
functionality.
Middleware Purpose
morgan Logs HTTP requests
cors Enables Cross-Origin Resource Sharing
helmet Adds security headers
cookie-parser Parses cookies in requests
Example: Using Morgan and CORS
npm install morgan cors
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const app = express();
[Link](morgan('dev'));
[Link](cors());
[Link]([Link]());
[Link]('/', (req, res) => [Link]('CORS and Morgan enabled!'));
[Link](3000, () => [Link]('Server running on port 3000'));

9. Custom Middleware for Request Processing


Example: Validate Request Data
const validateUser = (req, res, next) => {
if (![Link]) {
return [Link](400).send('Name is required');
}
next();
};
[Link]('/users', validateUser, (req, res) => {
[Link](`User ${[Link]} added successfully`);
});
Explanation:
• Checks whether name field exists in the request body.
• If not, responds with status 400 Bad Request.
• If valid, passes control to the route handler.

10. Error-Handling Middleware


10.1 What is Error-Handling Middleware?
• Special middleware to handle runtime errors in the application.
• Must have four parameters: (err, req, res, next).
• Prevents server crashes by catching and handling unexpected errors.
10.2 Syntax
[Link]((err, req, res, next) => {
[Link]([Link]); // log error details
[Link](500).send('Something went wrong!');
});
10.3 Example
[Link]('/error', (req, res) => {
throw new Error('Test error');
});
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).json({ error: [Link] });
});
Explanation:
• The route intentionally throws an error.
• The error-handling middleware catches it and responds with an appropriate
message.

11. Order of Middleware Execution


• The order of middleware registration determines execution order.
• Middleware is executed in the sequence it is defined in the code.
Example:
[Link](firstMiddleware);
[Link](secondMiddleware);
[Link]('/', routeHandler);
Execution Order:
firstMiddleware → secondMiddleware → routeHandler
If next() is not called in any middleware, the chain stops there.
12. Global Error Handling Workflow
Flow Diagram (Conceptual):
Request

Application Middleware (e.g., logger, parser)

Route Handler (GET, POST, etc.)

If Error → Error-Handling Middleware

Response Sent to Client

13. Summary
Concept Description
Middleware Function that processes requests before sending responses.
Application-level, Router-level, Built-in, Third-party, Error-
Types
handling.
next() Passes control to the next middleware.
Error Handling Uses 4-parameter middleware (err, req, res, next).
Order of
Middleware runs in the order they are defined.
Execution

14. Best Practices for Middleware Implementation


1. Keep middleware functions modular and reusable.
2. Use error-handling middleware as the last middleware in the stack.
3. Place logging and parsing middleware at the top.
4. Use third-party libraries for security (e.g., helmet, cors).
5. Avoid heavy logic inside middleware — delegate to controllers when possible.
6. Always include next() unless you send a response or end the cycle.
INTEGRATING MONGODB AS THE DATABASE USING MONGOOSE ORM

1. Introduction
1.1 What is MongoDB?
• MongoDB is a NoSQL database that stores data in JSON-like documents called BSON
(Binary JSON).
• It is document-oriented, schema-less, and supports scalable and high-performance data
storage.
1.2 Key Features of MongoDB
• Stores data as collections and documents (not tables and rows).
• Schema-flexible: Documents in the same collection can have different structures.
• Supports indexing, aggregation, and replication for performance and reliability.
• Ideal for modern web applications that deal with unstructured or semi-structured data.

2. What is Mongoose?
2.1 Definition
• Mongoose is an Object Data Modeling (ODM) library for [Link] that provides a structured
way to interact with MongoDB.
• It acts as a bridge between application objects and MongoDB documents.
2.2 Why Use Mongoose?
Mongoose simplifies database interactions by:
• Defining schemas for collections.
• Validating data before saving.
• Managing relationships between data.
• Providing an easy-to-use API for CRUD operations.

3. Mongoose vs MongoDB Native Driver


Feature Mongoose MongoDB Native Driver
Abstraction Level High-level ODM Low-level API
Schema Schema-based Schema-less
Validation Built-in Manual implementation
Relationships Supports references and population Manual joins using aggregation
Ease of Use Easier and more structured Requires more code

4. Installing and Setting up MongoDB and Mongoose


4.1 Prerequisites
• [Link] and npm installed
• MongoDB installed and running (locally or using a cloud service like MongoDB Atlas)
4.2 Installation Commands
npm install mongoose
If MongoDB is not installed locally, you can use a MongoDB Atlas connection string.

5. Connecting MongoDB with [Link] using Mongoose


Example:
const mongoose = require('mongoose');

// Connection URL (Local or Cloud)


const uri = 'mongodb://localhost:27017/mydatabase';
// Connecting to MongoDB
[Link](uri, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => [Link]('MongoDB Connected Successfully'))
.catch(err => [Link]('Connection Error:', err));
Explanation:
• [Link]() establishes a connection to the MongoDB database.
• The connection string specifies the database name and host.
• Promises handle success and failure responses.

6. Defining a Schema in Mongoose


A Schema defines the structure of a document — similar to defining a table structure in SQL.
Example:
const mongoose = require('mongoose');
const userSchema = new [Link]({
name: { type: String, required: true },
age: Number,
email: { type: String, required: true, unique: true },
createdAt: { type: Date, default: [Link] }
});
Explanation:
Field Type Description
name String Required field for storing the user's name
age Number Optional numeric field
email String Unique and required field
createdAt Date Automatically stores the timestamp when created

7. Creating a Model
A Model is a compiled version of the Schema — it represents a MongoDB collection.
Example:
const User = [Link]('User', userSchema);
• The first argument 'User' is the model name.
• Mongoose automatically creates a collection named 'users' (plural form).

8. Performing CRUD Operations with Mongoose


8.1 Create (Insert Data)
const newUser = new User({
name: 'Alice',
age: 25,
email: 'alice@[Link]'
});
[Link]()
.then(() => [Link]('User Saved Successfully'))
.catch(err => [Link]('Error Saving User:', err));
8.2 Read (Retrieve Data)
[Link]()
.then(users => [Link](users))
.catch(err => [Link](err));
Find by Condition
[Link]({ email: 'alice@[Link]' })
.then(user => [Link](user));
8.3 Update
[Link]({ name: 'Alice' }, { age: 26 })
.then(() => [Link]('User Updated'))
.catch(err => [Link](err));
8.4 Delete
[Link]({ email: 'alice@[Link]' })
.then(() => [Link]('User Deleted'))
.catch(err => [Link](err));

9. Schema Validation and Constraints


Mongoose supports built-in validation to ensure data integrity.
Example:
const productSchema = new [Link]({
name: { type: String, required: [true, 'Product name is required'] },
price: { type: Number, min: [0, 'Price cannot be negative'] },
inStock: { type: Boolean, default: true }
});
Validation Rules:
Validator Description
required Ensures field must have a value
unique Ensures field values are not duplicated
min / max Restrict numeric range
match Validates against a regex pattern
default Sets default value if not provided

10. Relationships in Mongoose


MongoDB is non-relational, but Mongoose allows references between collections using
ObjectId.
Example: One-to-Many Relationship
const postSchema = new [Link]({
title: String,
content: String,
author: { type: [Link], ref: 'User' }
});
Populating Data
[Link]()
.populate('author')
.then(posts => [Link](posts));
Explanation:
• The author field references a document in the User collection.
• .populate('author') replaces the ObjectId with full user data.
11. Middleware (Hooks) in Mongoose
Mongoose allows you to define pre and post hooks to perform actions before or after database
operations.
Example:
[Link]('save', function(next) {
[Link]('About to save user:', [Link]);
next();
});
Common Middleware Hooks:
Hook Description
pre('save') Runs before saving a document
post('save') Runs after a document is saved
pre('remove') Runs before a document is deleted

12. Using MongoDB Atlas (Cloud Integration)


MongoDB Atlas provides a cloud-hosted MongoDB database.
Steps to Connect:
1. Create a free account at [Link]
2. Create a cluster and database.
3. Obtain the connection string (URI):
4. mongodb+srv://<username>:<password>@[Link]/mydatabase
5. Replace it in your [Link]():
6. [Link]('mongodb+srv://user:pass@[Link]/mydatabase');

13. Example: Complete CRUD API using Express and Mongoose


const express = require('express');
const mongoose = require('mongoose');
const app = express();
[Link]([Link]());
// Connect to MongoDB
[Link]('mongodb://localhost:27017/testdb', { useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => [Link]('MongoDB connected'))
.catch(err => [Link](err));
// Define Schema and Model
const userSchema = new [Link]({
name: String,
email: String
});
const User = [Link]('User', userSchema);
// Routes
[Link]('/users', async (req, res) => {
const users = await [Link]();
[Link](users); });
[Link]('/users', async (req, res) => {
const newUser = new User([Link]);
await [Link]();
[Link](newUser);
});
[Link](3000, () => [Link]('Server running on port 3000'));
14. Advantages of Using Mongoose
Feature Description
Schema Definition Defines document structure clearly
Data Validation Ensures consistency and correctness
Middleware Support Allows pre/post database hooks
Query Simplification Provides chainable and readable methods
Relationship Handling Supports data referencing and population
Integration Works seamlessly with Express for full-stack apps

15. Summary
Concept Description
MongoDB NoSQL document-oriented database
Mongoose ODM library for MongoDB in [Link]
Schema Defines structure of documents
Model Represents a MongoDB collection
CRUD Operations Create, Read, Update, Delete operations
Validation Enforces data consistency
Relationships Managed via ObjectId references
Atlas Cloud-based MongoDB service
PROJECT: BUILDING A RESTFUL API BACKEND FOR A WEB APPLICATION

1. Introduction
1.1 What is a RESTful API Backend?
• A RESTful API backend is the server-side component of a web application that
handles:
o Data storage (using a database like MongoDB or MySQL)
o Business logic (rules and validations)
o Communication with the frontend via HTTP requests and responses
• It exposes data and services through RESTful endpoints, which can be accessed by:
o Frontend web applications (React, Angular, etc.)
o Mobile apps
o External systems or APIs
1.2 Goal of the Project
To design and develop a fully functional RESTful API using:
• [Link] for server-side JavaScript execution
• [Link] for routing and HTTP handling
• MongoDB with Mongoose ORM for database integration
This project represents the backend foundation of a full-stack web application.

2. Project Objectives
1. Set up a [Link] + Express server.
2. Connect the application to a MongoDB database using Mongoose.
3. Implement RESTful routes for CRUD operations.
4. Include middleware for request validation and error handling.
5. Test the API using tools like Postman or Insomnia.
6. Ensure modular, scalable, and maintainable code organization.

3. Tools and Technologies Used


Category Tool / Framework Description
Runtime [Link] JavaScript runtime environment
Web application framework for
Framework [Link]
[Link]
Database MongoDB NoSQL database for data storage
Object Data Modeling tool for
ORM Mongoose
MongoDB
Testing Postman API testing tool
Version Control Git & GitHub Source code management
Development
Visual Studio Code IDE for coding
Environment
4. RESTful API Architecture Overview
4.1 Components
1. Client – Frontend or external service making API requests.
2. Server – [Link] + Express backend processing requests.
3. Database – MongoDB storing application data.
4. Routes – Define API endpoints (URLs).
5. Controllers – Handle logic for each route.
6. Models – Represent data structure using Mongoose schemas.
4.2 REST Principles Recap
HTTP
Operation Example Endpoint Description
Method
Add new
Create POST /api/products
resource
Read /api/products, Retrieve
GET
(List/Single) /api/products/:id resource(s)
Update PUT/PATCH /api/products/:id Modify resource
Delete DELETE /api/products/:id Remove resource

5. Project Setup
Step 1: Initialize the Project
mkdir rest-api-project
cd rest-api-project
npm init -y
npm install express mongoose dotenv cors
Step 2: Project Structure
rest-api-project/

├── [Link] # Entry point
├── .env # Environment variables
├── [Link]

├── config/
│ └── [Link] # Database connection

├── models/
│ └── [Link] # Mongoose schema

├── routes/
│ └── [Link] # Express routes

└── controllers/
└── [Link] # Business logic
6. Step-by-Step Implementation
6.1 Configure Environment Variables
.env
PORT=4000
MONGO_URI=mongodb://localhost:27017/productDB

6.2 Database Connection


config/[Link]
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await [Link]([Link].MONGO_URI);
[Link]('MongoDB Connected Successfully');
} catch (error) {
[Link]('Database Connection Failed:', [Link]);
[Link](1);
}
};
[Link] = connectDB;

6.3 Define a Mongoose Schema


models/[Link]
const mongoose = require('mongoose');
const productSchema = new [Link]({
name: { type: String, required: true },
category: String,
price: { type: Number, required: true },
inStock: { type: Boolean, default: true },
createdAt: { type: Date, default: [Link] }
});
[Link] = [Link]('Product', productSchema);

6.4 Create Controller Logic


controllers/[Link]
const Product = require('../models/productModel');
// Create
[Link] = async (req, res) => {
try {
const product = await [Link]([Link]);
[Link](201).json(product);
} catch (error) {
[Link](400).json({ message: [Link] });
}
};
// Read All
[Link] = async (req, res) => {
const products = await [Link]();
[Link](200).json(products);
};
// Read One
[Link] = async (req, res) => {
try {
const product = await [Link]([Link]);
if (!product) return [Link](404).json({ message: 'Product not found' });
[Link](product);
} catch (error) {
[Link](500).json({ message: [Link] });
}
};
// Update
[Link] = async (req, res) => {
try {
const product = await [Link]([Link], [Link], { new:
true });
[Link](product);
} catch (error) {
[Link](400).json({ message: [Link] });
}
};
// Delete
[Link] = async (req, res) => {
try {
await [Link]([Link]);
[Link]({ message: 'Product deleted successfully' });
} catch (error) {
[Link](500).json({ message: [Link] });
}
};

6.5 Define Express Routes


routes/[Link]
const express = require('express');
const router = [Link]();
const productController = require('../controllers/productController');
[Link]('/', [Link]);
[Link]('/', [Link]);
[Link]('/:id', [Link]);
[Link]('/:id', [Link]);
[Link]('/:id', [Link]);
[Link] = router;
6.6 Main Server File
[Link]
const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const connectDB = require('./config/db');
const productRoutes = require('./routes/productRoutes');
[Link]();
connectDB();
const app = express();
[Link](cors());
[Link]([Link]());
[Link]('/api/products', productRoutes);
const PORT = [Link] || 4000;
[Link](PORT, () => [Link](`Server running on port ${PORT}`));

7. Testing the API with Postman


Endpoints to Test:
Method Endpoint Description Example Body
{ "name": "Laptop",
POST /api/products Create a new product
"price": 55000 }
GET /api/products Fetch all products –
GET /api/products/:id Fetch a product by ID –
PUT /api/products/:id Update a product { "price": 60000 }
DELETE /api/products/:id Delete a product –

8. Implementing Error Handling


Global Error Middleware
Add this at the end of [Link]:
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).json({ message: 'Internal Server Error' });
});
This ensures unexpected errors are caught and returned in a consistent format.

9. Enhancements and Best Practices


Feature Description
Validation Use Mongoose schema validation or Joi library.
Authentication Protect routes using JWT (JSON Web Tokens).
Pagination Implement pagination for large datasets.
Search & Filter Add query parameters for flexible data retrieval.
Environment Variables Store credentials in .env file, never hard-code them.
Error Logging Use libraries like morgan or winston for better debugging.
10. Example Folder Organization (Scalable Project)
rest-api-project/
├── config/
│ └── [Link]
├── controllers/
│ └── [Link]
├── middleware/
│ └── [Link]
├── models/
│ └── [Link]
├── routes/
│ └── [Link]
├── [Link]
└── .env

11. Summary
Concept Description
Provides a fast, modular server framework for
[Link] + Express
handling API requests.
MongoDB + Offers flexible NoSQL data storage and schema
Mongoose modeling.
Uses standard HTTP methods and endpoints for
RESTful Design
CRUD operations.
Handles request parsing, logging, authentication,
Middleware
and errors.
Testing (Postman) Ensures correctness of API functionality.

You might also like