Develop A Backend Application With Node - Js
Develop A Backend Application With Node - Js
TRAINER:SAMIE TWAHIRWA
Ele
TABLE OF CONTENT
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:
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.
Model-View-Controller (MVC):
Controller: Manages the flow of data between the Model and View.
Model-View-Controller-Service (MVCS):
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.
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
cd node-rest-api
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).
From here on, you can run all your commands in your editor’s terminal.
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:
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:
Create a new file called config.js. In this file, we’ll add the following code to
set a default port:
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);
});
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:
response.send(status);
});
Exercises:
Middleware
Database Integration
API Documentation
Descriptions:
Using Mongoose
newUser.save()
.then(() => console.log('User created'))
.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));
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.
mongoose.connect('mongodb://localhost/my_database', {
useNewUrlParser: true });
const db = mongoose.connection;
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.
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.
try {
const user = new User({ name, email, age });
await user.save();
res.send(user);
} 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);
}
});
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:
app.use(bodyParser.json());
app.use('/', routes);
app.listen(3000, () => {
console.log('Server started on port 3000');
});
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:
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:
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:
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.
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.
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.
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 2:
End Of Note.