Web II Working With Restful Apis Lesson014
Web II Working With Restful Apis Lesson014
RESTful APIs are a popular way of creating web applications that exchange data
over the internet in a standardized manner. These APIs follow specific principles
such as using resource-based URLs and HTTP methods to perform various
operations like creating, reading, updating, and deleting data. Express js is a
powerful framework that allows developers to easily create routes, handle requests,
and send responses, making it a versatile choice for building APIs that are robust
and scalable.
Understanding the concept of RESTful APIs in Express JS:
REST Architecture: REST, which stands for Representational State
Transfer, is an architectural style for designing networked applications.
Resource-Based: RESTful APIs in ExpressJS are designed around
resources, which are identified by unique URLs. These resources represent
the entities (e.g., users, products, articles) that the API manipulates.
HTTP Methods: RESTful APIs use standard HTTP methods to
perform CRUD (Create, Read, Update, Delete) operations on resources:
o GET: Retrieves data from a resource.
o POST: Creates a new resource.
o PUT: Updates an existing resource.
o DELETE: Deletes a resource.
Statelessness: RESTful APIs are stateless, meaning that each request from a
client contains all the information needed to process the request. Servers do
not maintain a session state between requests.
Uniform Interface: RESTful APIs have a uniform interface, which
simplifies communication between clients and servers. This interface
typically involves the use of standard HTTP methods, resource identifiers
(URLs), and representations (e.g., JSON, XML).
ExpressJS and Routing: In ExpressJS, you define routes to handle
incoming requests for specific resources and HTTP methods. Each route
specifies a callback function to process the request and send an appropriate
response.
Middleware Integration: ExpressJS middleware can be used to handle
tasks such as request validation, authentication, and response formatting,
enhancing the functionality and security of RESTful APIs.
Response Codes: RESTful APIs use standard HTTP status codes to indicate
the success or failure of a request. Common status codes include 200 (OK),
201 (Created), 400 (Bad Request), 404 (Not Found), and 500 (Internal
Server Error).
res.json(filteredUsers);
};
if (!name || !email) {
return res.status(400).json({
error: 'Both name and email are required'
});
}
if (!name || !email) {
return res.status(400).json({
error: 'Both name and email are required for full update'
});
}
res.json(userToUpdate);
};
DELETE: Deletes a resource.
const deleteUser = (req, res) => {
const id = parseInt(req.params.id);
const userIndex = users.findIndex(u => u.id === id);
router.get('/', usersController.getUsers);
router.post('/', usersController.createUser);
router.get('/:id', usersController.getUserById);
router.put('/:id', usersController.updateUser);
router.delete('/:id', usersController.deleteUser);
module.exports = router;
server.js
const express = require('express');
const app = express();
app.use(express.json());
app.use('/api/users', userRoutes);
controllers/users.js
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
// GET /api/users
const getUsers = (req, res) => {
// Access query parameters
const { name, email } = req.query;
res.json(filteredUsers);
};
// POST /api/users
const createUser = (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({
error: 'Both name and email are required'
});
}
// GET /api/users/:id
const getUserById = (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
};
res.json(userToUpdate);
};
// DELETE /api/users/:id
const deleteUser = (req, res) => {
const id = parseInt(req.params.id);
const userIndex = users.findIndex(u => u.id === id);
module.exports = {
getUsers,
createUser,
getUserById,
updateUser,
patchUser,
deleteUser
};