0% found this document useful (1 vote)
481 views26 pages

Develop A Backend Application With Node - Js

The document provides instructions for developing a backend application with Node.js. It discusses setting up a development environment with Node.js and Express, defining RESTful APIs with routes and endpoints, and testing and deploying the application. Key steps include installing Node.js, initializing an app, installing dependencies like Express, defining routes and endpoints to handle requests, and setting up the server to listen on a specified port. Testing and security measures are also recommended.

Uploaded by

gudonion
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (1 vote)
481 views26 pages

Develop A Backend Application With Node - Js

The document provides instructions for developing a backend application with Node.js. It discusses setting up a development environment with Node.js and Express, defining RESTful APIs with routes and endpoints, and testing and deploying the application. Key steps include installing Node.js, initializing an app, installing dependencies like Express, defining routes and endpoints to handle requests, and setting up the server to listen on a specified port. Testing and security measures are also recommended.

Uploaded by

gudonion
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 26

RWANDA TVET BOARD Kigali-Rwanda

ACADEMIC YEAR 2023-2024 World Mission High School


SECTOR:ICT
TRADE:SOFTWARE DEVELOPMENT
LEVEL:4
MODULE:DEVELOP A BACKEND APPLICATION WITH NODE.JS
CODE:SWDBD 401

TRAINER:SAMIE TWAHIRWA

Ele
TABLE OF CONTENT

Unit 1. Develop RESTFUL APIs with Node JS


1.1 Development environment is properly arranged based on coding
architecture methodology
1.2 Server and database connection are properly established according to
development environment
1.3 RESTFUL APIs are effectively implemented based on backend
functionalities

Unit 2.Secure Backend Application


2.1 Data encryption is correctly applied based on system security
2.2 Third-party libraries are carefully checked based on system security
2.3 User Authentication, Authorization and Accountability (AAA) are
carefully applied based on NPM Universal Access Control (UAC)
2.4 Environment variables are carefully Secured according to system security

Unit 3. Test Backend Application


3.1 Unit tests are appropriately conducted based on software testing
techniques
3.2 Usability is correctly tested according to expected results
3.3 Security is properly tested based on system threats

Unit 4.Manage Backend Application


4.1 Application is appropriately deployed based on FURPS requirements
4.2 Backend is effectively maintained according to the system Functionalities
4.3 Application documentation is properly generated according to the
system backend
Unit 1. Develop RESTFUL APIs with Node JS

1.1 Development environment is properly arranged based on coding architecture


methodology

What is a REST API?

REST, which stands for REpresentational State Transfer, is a software


development architecture that defines a set of rules for communication
between a client and a server. Let’s break this down a little more:

 A REST client is a code or app used to communicate with REST servers.


 A server contains resources that the client wants to access or change.
 A resource is any information that the API can return.

A REST API, also known as a RESTful API, is an API that conforms to the REST
architecture. These APIs use the HTTP protocol to access and manipulate data on
the server.

The essential components of a REST API include the HTTP method, endpoint,
headers, and body. Here’s an example of a REST API that gives you a list of
astronauts who are currently in space.

HTTP methods

The HTTP method defines the action the client wants to make on the server,
which includes creating, reading, updating, or deleting resources (CRUD). Here
are four HTTP methods that are commonly used in REST APIs:

 GET: used to retrieve resources.


 POST: used to add resources.
 PUT: used to update resources.
 DELETE: used to delete resources.

What is Node.js?
By definition, Node.js is an open source and cross-platform JavaScript runtime
environment that runs based on Chrome’s V8 engine.
Why should you use Node.js and Express to
build your REST API?
Here are four key advantages of Node.js and Express:

1. The ability to use a single language (JavaScript) for both client-side and
server-side development.
2. Fast and powerful performance, owing to the ability to run multiple requests
in parallel.
3. Middleware and routing capabilities that are built into Express to make API
development quick and easy.
4. A large, active community of developers contributing to the ecosystem.

Choosing the Right Coding Architecture Methodology:

The choice of coding architecture methodology plays a vital role in


how your Restful API will be structured and developed. Two popular
methodologies that work well with Node.js are the Model-View-
Controller (MVC) and the Model-View-Controller-Service (MVCS)
patterns.

Model-View-Controller (MVC):

Model: Represents the data and database interactions.

View: Handles user interface and presentation.

Controller: Manages the flow of data between the Model and View.

Model-View-Controller-Service (MVCS):

Model: Data and database logic.

View: User interface and presentation.

Controller: Routes HTTP requests.

Service: Business logic and data manipulation.


Setting Up the Development Environment:

To arrange a development environment based on your chosen


coding architecture methodology:

 Choose a Node.js Framework: Node.js frameworks like


Express.js are excellent for building Restful APIs. They provide
essential tools for routing, middleware, and request handling.
 Version Control: Use a version control system like Git to track
changes and collaborate with a team. Platforms like GitHub or
GitLab can help manage repositories.
 Project Structure: Organize your project files and directories
according to your chosen methodology. For example, if using
MVC, separate your code into "models," "views," and
"controllers" folders. In MVCS, include a "services" folder for
business logic.
 Dependency Management: Utilize npm (Node Package
Manager) to manage project dependencies. Maintain a
package.json file to keep track of packages and their versions.
 Database Integration: If your API interacts with a database,
choose an appropriate database system (e.g., MongoDB,
PostgreSQL) and set up database connections and schema
models accordingly.

 Middleware: Implement middleware for tasks like


authentication, logging, and error handling. Middleware helps in
maintaining a modular and organized codebase.
 Testing: Integrate testing frameworks like Mocha, Chai, or Jest
to ensure the reliability and quality of your API.
 Documentation: Create clear and comprehensive API
documentation using tools like Swagger or OpenAPI. Proper
documentation is essential for developers who will use your
API.
 Security: Implement security measures like input validation,
authentication, and authorization to protect your API from
potential threats.
 Continuous Integration/Continuous Deployment (CI/CD): Set up
CI/CD pipelines to automate testing and deployment
processes, ensuring a smooth development workflow.

Setting up a Node.js app


Step 1: Install Node.js and NPM

The first thing we’ll need to do is install Node.js on our machine. You can
download the latest LTS version from the official Node.js website. Follow the
prompts in the Node.js Installer and customize the defaults, if necessary. When
you’re done, you should have installed Node.js, as well as NPM (Node Package
Manager). You can verify the installation by running the following commands in
your terminal:

node -v
npm -v

If you see the versions of Node.js and NPM show up, your installation was
successful.

Step 2: Create a new project folder

Next, we’ll create a new folder for the project by running the following
command in your terminal (note that entering this command as-is will name
your project “node rest api,” but you can change the name, if you’d like):

mkdir node-rest-api

To navigate to your project, enter this command:

cd node-rest-api

Step 3: Initialize a new Node.js application


To initialize your app, run the following command in your terminal:

npm init

You will be prompted to enter your project name, description, and GitHub
repository. You can accept the defaults by pressing Enter/Return, or customize
them.

Next, open this project in your editor, where you will see a new file
called package.json. This file contains the data you added about your project
in the terminal. It also describes how you’re going to run the project and lists its
dependencies (frameworks and libraries).

Step 4: Install Express and other dependencies

From here on, you can run all your commands in your editor’s terminal.

Run the following command to install the Express framework:

npm install express

Step 5: Import necessary modules

We’ll start by creating a new file named app.js in the root of the project
directory. We’ll use this file to set up the app. Then, we’ll load the dependencies
so we can use them. In the app.js file, add the following code to import
Express:

const express = require(‘express’);

Now, let’s set up Express to create an app and configure it to parse requests
with JSON payloads. Here’s the code you can add to do that:

const app = express ();


app.use(express.json());

Step 6: Define a route that listens to requests


Now we need to make this application a server by getting it to listen for
connections. To do this, we’ll connect to a port to listen for incoming requests.

Create a new file called config.js. In this file, we’ll add the following code to
set a default port:

const PORT = process.env.PORT || 3000;

With the process.env.PORT variable, we set up the port automatically by


allowing the API to be deployed to a cloud platform like AWS or Azure. In case
the process.env.PORT variable is not set, we’ll default to using port 3000.

Next, we’ll add the following code to the the app.js file in order to set up the
server to listen on the specified port:

app.listen(PORT, () => {
console.log("Server Listening on PORT:", port);
});

Step 7: Define an endpoint

Let’s start by defining a status endpoint to ensure the API is working.

Express lets you define routes using the app.METHOD() function. Here, METHOD
refers to the different HTTP methods, like GET, POST, PUT, and DELETE. For a
GET request, you’d define the route by adding an app.get() function. This
function has two parameters. We’ll use the first parameter to define the path. In
this case, it is the /status endpoint:

app.get(“/status”, ());

Next, we’ll add a callback function as the second parameter, which defines what
we will do when the request is called. This function has two parameters: the
request object (which contains details like the HTTP method, headers, and
request body) and the response object (which defines the information that we
want to send). The response (res) object contains different methods of sending
a response to the client, such as res.send(), res.json(), and res.render().
Here’s what it looks like now:

app.get(“/status”, (request, response));

With response.send(), we then define the response we want to return. But


since we want to send back JSON, we’ll need to first define a JSON object. So,
we define a status variable and create an object:

response.send(status) is now a function that takes the JSON object as


the argument.

app.get(“/status”, (request, response) => {


const status = {
“Status”: “Running”
};

response.send(status);
});

Exercises:

Exercise 1: Multiple Choice Which of the following is a popular


coding architecture methodology for setting up a development
environment? a) IDE b) API c) MVC d) CPU

Exercise 2: True or False True or False: Using a version control


system like Git is not necessary when setting up a development
environment.

Exercise 3: Fill in the Blank The ____________ folder in the


project structure is responsible for managing the flow of data
between the Model and View in the MVC architecture.

Exercise 4: Short Answer Name two examples of Node.js


frameworks commonly used for building Restful APIs.
Exercise 5: Matching Match the following terms to their
corresponding descriptions:

Middleware

Continuous Integration/Continuous Deployment (CI/CD)

Database Integration

API Documentation

Descriptions:

Automates testing and deployment processes.

Handles tasks like authentication and error handling.

Involves connecting your API to a database system.

Provides clear and comprehensive information about your API for


developers.

1.2 Server and database connection are properly established according


to development environment

In the process of developing a RESTful API with Node.js, one of


the foundational pillars of success is the establishment of robust
server and database connections within the development
environment. A well-structured and properly configured connection
between the server and the database is crucial for the API's
performance, security, and scalability. This note highlights the
significance of establishing these connections in the context of
developing a RESTful API using Node.js.

In a development environment, ensuring the proper establishment


of server and database connections is essential for the smooth
functioning of applications. Here are some best practices to follow:
Introduction

In Node.js, databases are used to store and retrieve data for


web applications. They are an essential part of building
dynamic and scalable applications. Node.js provides various
modules and packages to work with databases such as MySQL,
PostgreSQL, MongoDB, and more. They allow developers to
store, query, and manipulate data using various operations
such as create, read, update, and delete (CRUD).

They are particularly useful in web applications where data


needs to be stored and retrieved quickly and efficiently. For
example, an eCommerce website may use a database to store
product information, user data, and order details. A social
media application may use a database to store user profiles,
posts, and comments.

In addition to storing data, databases also provide features


such as data indexing, data integrity, and data security. These
features ensure that data is stored and accessed correctly and
securely.

Hence they are a critical component of web application


development in Node.js, and developers must have a good
understanding of how to work with databases and how to use
them efficiently to build robust applications.

Databases and ORMs


Databases and ORMs (Object Relational Mappers) play a vital
role in building web applications using Node.js. As described, a
database is a collection of data that is organized in a specific
manner to enable easy access, management, and updating of
information. In a Node.js application, databases are used to
store and retrieve data.

An ORM is a programming technique that maps objects to


relational database tables. ORMs provide a higher level of
abstraction, making it easier for developers to work with
databases by allowing them to interact with the database using
objects rather than SQL queries. ORMs help to reduce the
amount of code needed to interact with databases and provide
an additional layer of security by preventing SQL injection
attacks.

Node.js supports both SQL and NoSQL databases, including


PostgreSQL, MySQL, MongoDB, and Redis. The choice of
database depends on the application’s needs and
requirements. SQL databases are best suited for applications
that require complex queries and transactions, while NoSQL
databases are suitable for applications that require flexibility
and scalability.

Mongoose is a popular ORM for Node.js that provides a


schema-based solution to model the application data.
Mongoose simplifies the interaction with MongoDB by
allowing developers to define schemas and models for their
data. The schema defines the structure of the data and the
models represent the collection of data in the database.

Using Mongoose

As described above, ORMs (Object-Relational Mapping) are


used to simplify the process of interacting with databases,
making it easier to perform CRUD (Create, Read, Update,
Delete) operations by using object-oriented programming
concepts rather than directly writing SQL queries. With ORMs,
developers can work with data in a more intuitive and efficient
way, increasing productivity and reducing errors.

Mongoose is a popular ORM for MongoDB in Node.js. It


provides a schema-based solution to model application data
and provides features like validation, middleware, and more.
Here’s an example of how to use Mongoose in a Node.js
application:

First, install Mongoose using npm:

npm install mongoose

Then, create a connection to the MongoDB database using


Mongoose:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database', {
useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch((err) => console.log(err));

This code connects to a local MongoDB database


named my_database and logs a message to the console when the
connection is successful.

Next, define a Mongoose schema for the data that will be


stored in the database:

const mongoose = require('mongoose');


const Schema = mongoose.Schema;

const userSchema = new Schema({


name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});

module.exports = mongoose.model('User', userSchema);


This code defines a schema for a user object that includes a
name, email, password, and createdAt property.
The required property specifies that certain fields are
mandatory, and the unique property ensures that each email
address can only be used once.

Finally, use the defined schema to create, read, update, and


delete documents in the database:

const User = require('./models/user');

// Create a new user


const newUser = new User({
name: 'John Doe',
email: 'johndoe@example.com',
password: 'password123'
});

newUser.save()
.then(() => console.log('User created'))
.catch((err) => console.log(err));

// Read all users


User.find()
.then((users) => console.log(users))
.catch((err) => console.log(err));

// Update a user
User.findOneAndUpdate({ name: 'John Doe' }, { name: 'Jane Doe' })
.then(() => console.log('User updated'))
.catch((err) => console.log(err));

// Delete a user
User.deleteOne({ name: 'Jane Doe' })
.then(() => console.log('User deleted'))
.catch((err) => console.log(err));

In this example, the User model is imported from the


previously defined schema file. A new user is created using
the save() method, all users are read using the find() method, a
user is updated using the findOneAndUpdate() method, and a
user is deleted using the deleteOne() method. These methods
are all provided by Mongoose and simplify the process of
interacting with the database.

Basic Application Development

To create a Node.js application with Mongoose and perform


CRUD operations, we will follow these steps:

1. Initialize a new Node.js project.


2. Install the required dependencies (express, mongoose).
3. Set up the MongoDB database connection.
4. Create a Mongoose schema for our data.
5. Create routes to handle CRUD operations.
6. Test our application.

Step 1: Initialize a new Node.js project

To create a new Node.js project, we will use the npm package


manager. Open a command prompt or terminal window and
navigate to the folder where you want to create your project.

Type the following command to initialize a new Node.js


project:

npm init
This command will prompt you for information about your
project, such as the name, version, and author. You can either
enter the information or press enter to accept the default
values.

Step 2: Install the required dependencies

To install the required dependencies for our application, we


will use npm. In the same command prompt or terminal
window, type the following command:

npm install express mongoose

This command will install the Express.js and Mongoose


packages in your project.

Step 3: Set up the MongoDB database connection

In order to use Mongoose with MongoDB, we need to set up a


connection to our MongoDB database. We can do this by
creating a new file called db.js in the root directory of our
project, and adding the following code:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/my_database', {
useNewUrlParser: true });
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));


db.once('open', function() {
console.log('Database connected successfully');
});

This code connects to a MongoDB database called


“my_database” running on the local machine. If you have a
different database name or URL, you can change the
connection string accordingly.

Step 4: Create a Mongoose schema for our data

Now that we have set up our database connection, we can


create a Mongoose schema to define the structure of our data.
In this example, we will create a simple schema for a “User”
model.

Create a new file called user.js in the root directory of our


project, and add the following code:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({


name: String,
email: String,
age: Number
});

const User = mongoose.model('User', userSchema);

module.exports = User;
This code defines a Mongoose schema with three fields:
“name”, “email”, and “age”. We then create a Mongoose model
called “User” using this schema, and export it for use in other
parts of our application.

Step 5: Create routes to handle CRUD operations

Now that we have our database connection and schema set up,
we can create routes to handle CRUD (create, read, update,
delete) operations on our data.

Create a new file called routes.js in the root directory of our


project, and add the following code:

const express = require('express');


const User = require('./user');

const router = express.Router();

// Create a new user


router.post('/users', async (req, res) => {
const { name, email, age } = req.body;

try {
const user = new User({ name, email, age });
await user.save();
res.send(user);
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});

// Get all users


router.get('/users', async (req, res) => {
try {
const users = await User.find({});
res.send(users);
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});

// Update a user
router.put('/users/:id', async (req, res) => {
const { id } = req.params;
const { name, email, age } = req.body;

try {
const user = await User.findByIdAndUpdate(id, { name, email, age
}, { new: true });
res.send(user);
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});

// Delete a user
router.delete('/users/:id', async (req, res) => {
const { id } = req.params;

try {
const user = await User.findByIdAndDelete(id);
res.send(user);
} catch (error) {
console.error(error);
res.status(500).send(error);
}
});

Step 6: Test our application

Now that we have created all the necessary routes, we can test
our application. Create a new file called index.js in the root
directory of our project, and add the following code:

const express = require('express');


const bodyParser = require('body-parser');
const db = require('./db');
const routes = require('./routes');
const app = express();

app.use(bodyParser.json());

app.use('/', routes);

app.listen(3000, () => {
console.log('Server started on port 3000');
});

This code sets up an Express.js server, adds the middleware for


parsing JSON request bodies, and sets up the routes we
created earlier. It also starts the server and logs a message to
the console to indicate that it is running.

To test our application, we can use a tool like Postman or curl


to send requests to the server. For example, to create a new
user, we can send a POST request
to http://localhost:3000/users with a JSON body containing the
user's name, email, and age. To get all users, we can send a
GET request to http://localhost:3000/users.

That’s it! We have created a basic Node.js application with


Mongoose and performed CRUD operations on a MongoDB
database. Of course, this is just a starting point — you can
customize the application and schema to fit your needs.

1.3 RESTFUL APIs are effectively implemented based on backend


functionalities

RESTful APIs serve as the backbone of modern web applications, providing a scalable
and flexible way for front-end clients to communicate with backend services. When
implementing RESTful APIs using Node.js, several best practices can ensure their
effectiveness and reliability:
Use Express.js:

Utilize Express.js, a minimalist Node.js framework, to simplify route handling and


middleware management. Express.js provides robust tools for building RESTful APIs
efficiently.

Route Organization:

Organize routes logically and follow RESTful conventions. Use HTTP methods (GET,
POST, PUT, DELETE) for CRUD operations and resource endpoints (e.g., /users,
/products) for clear API structure.

Middleware Implementation:

Implement middleware functions for tasks such as authentication, input validation,


error handling, and logging. Middleware ensures consistent behavior across API
endpoints.

Data Validation and Sanitization:

Validate and sanitize input data to prevent malicious attacks like SQL injection and
XSS attacks. Libraries like express-validator can help validate and sanitize user input
effectively.

Error Handling:

Centralize error handling to provide consistent error responses. Use try-catch blocks
and middleware functions to catch errors and format them into meaningful error
messages for clients.

Asynchronous Operations:

Use asynchronous programming patterns, such as async/await or Promises, to


handle I/O operations and database queries. This prevents blocking the event loop
and ensures the API remains responsive under load.

Database Integration:

Integrate with databases using appropriate libraries (e.g., Mongoose for MongoDB,
Sequelize for SQL databases). Use connection pooling and efficient querying
techniques to optimize database interactions.

Authentication and Authorization:

Implement secure authentication mechanisms like JWT (JSON Web Tokens) for user
authentication. Use middleware to check user roles and permissions, ensuring
authorized access to API endpoints.
CORS Configuration:

Configure Cross-Origin Resource Sharing (CORS) to specify which origins are allowed
to access the API. Use middleware like cors to prevent unauthorized cross-origin
requests.

Testing and Documentation:

Write comprehensive unit tests using testing libraries like Mocha, Chai, or Jest to
validate API endpoints and functionality.
Document the API endpoints, request parameters, response formats, and error
codes using tools like Swagger or Postman. Clear documentation facilitates easy
integration for front-end developers and third-party consumers.

Security Best Practices:

Secure sensitive data, such as API keys and database credentials, using environment
variables. Avoid hardcoding these values in the source code.
Regularly update Node.js and its dependencies to patch security vulnerabilities.
PRACTICE SESSIONS

Project 1:create a project involves creating a basic RESTful


API using the Flask framework to manage a list of tasks. Users
can add, retrieve, update, and delete tasks. You'll also need to
set up a SQLite database to store task data.

Project 2:

Project Question: Building a To-Do List Application


Description:
You are tasked with building a basic To-Do List application that
allows users to create, read, update, and delete tasks. The
application should provide a RESTful API for managing tasks,
and tasks should be stored in a SQLite database. You should use
the Flask framework for building the API

End Of Note.

You might also like