REST API Using Express - Coding Ninjas
REST API Using Express - Coding Ninjas
Understanding API
Types of APIs
RESTful API
● Representational State Transfer is an architectural style for designing
networked applications that use standard HTTP protocols to communicate
between the client and server. REST APIs are built on top of the HTTP
protocol and work with resources identified by URLs.
● It is an Architectural Guideline
● It is popularly used across different types of systems.
REST Methods
REST APIs use standard HTTP methods like GET, POST, PUT, and DELETE to
perform operations on resources.
● GET requests to retrieve information about a resource or a collection of
resources.
● POST requests create a new resource.
● PUT requests to update an existing resource.
● DELETE requests remove a resource.
Applications of REST
REST APIs play a crucial role in modern web applications, allowing them to
efficiently communicate and exchange data with various systems. Some common
applications of REST APIs include:
● Integrating with third-party services: REST APIs can be used to interact
with external services like social media platforms, payment gateways, or
analytics tools, adding more functionality to your web application.
● Creating a consistent backend for multiple platforms: REST APIs can
serve as a common backend for web, mobile, and desktop applications,
ensuring that all platforms access the same data and logic.
● Developing microservices: REST APIs can be used to break down a
monolithic application into smaller, more manageable microservices,
improving scalability and maintainability.
E-Commerce APIs
Creating Folder Structure
// 2. Create Server
const server = express();
// 4. Specify port
server.listen(3200);
3. Create a new folder named "src" inside the "E-COM-API" folder to store the
source code of the application.
4. Inside the "src" folder, create a folder named “features”
5. Inside the "features" folder, create separate folders for different modules of
the application such as "cart", "order", "product", and "user". These folders
will contain the respective module-related files.
6. Additionally, create a folder named "middlewares" inside the "src" folder to
store middleware files that will be used in the application.
Setting Up Routes For Product
1. The goal is to create APIs related to products in the E-COM-API project.
4. A separate folder for controllers can be created within the product module to
manage multiple controllers.
7. Express router module is used to handle paths from the server to controller
methods.
8. The product roots file manages the paths to the product controller.
11. The product roots file specifies the paths and calls the respective controller
methods.
12. Other routes for different modules like user and order can be implemented
similarly.
13. Separate route files are recommended for each feature to maintain a modular
structure.
addProduct(request, response) {
// Code for adding a product
}
rateProduct(request, response) {
// Code for rating a product
}
getOneProduct(request, response) {
// Code for getting one product
}
}
app.use('/api/products', productRoutes);
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Product Model
1. Create the product model class in "product.model.js":
export default class ProductModel {
constructor(ID, name, description, imageURL, category,
price, sizes) {
this.ID = ID;
this.name = name;
this.description = description;
this.imageURL = imageURL;
this.category = category;
this.price = price;
this.sizes = sizes;
}
static getAll() {
// Returns all the products
return [
new ProductModel(1, "Product 1", "Description 1",
"image1.jpg", 1, 9.99, []),
new ProductModel(2, "Product 2", "Description 2",
"image2.jpg", 2, 19.99, ["M", "XL"]),
new ProductModel(3, "Product 3", "Description 3",
"image3.jpg", 3, 29.99, ["S"]),
];
}
}
Explanation:
● The product model is created as a class with properties such as ID,
name, description, imageURL, category, price, and sizes.
● The constructor initializes these properties when a new product object
is created.
● The static method getAll() returns an array of product objects. These
objects represent the default products in the system.
Explanation:
● The product controller imports the ProductModel class from the
product.model.js file.
● The getAllProducts function is a request handler for the route that
retrieves all products.
● Inside the function, it calls the static getAll() method of the
ProductModel to retrieve the products.
● The retrieved products are sent as the response using res.send().
● The status code 200 (OK) is set to indicate a successful response.
router.get('/', productController.getAllProducts);
module.exports = router;
Explanation:
● The product router is created using express.Router().
● The router is configured to handle a GET request at the root path ("/")
and call the getAllProducts function from the product controller.
● The router is exported to be used in the server file.
server.use("/api/products", productRoutes);
server.get("/",(req, res)=>{
res.send("Server is Ready at 4100");
})
server.listen(4100);
console.log("Server is listening on 4100");
Explanation:
● The product router is imported from the "product.router.js" file.
● The router is used as middleware with the base path '/api/products'.
● When a request is made to the server with the path '/api/products', it
will be handled by the product router.
● The server listens on the specified port (3000) and logs a message
when it is running.
static getAll() {
return [
// Default products
// ...
];
}
}
// ...
// ...
app.use('/api/products', productRouter);
For Testing:
Access http://localhost:<port>/api/products in the browser.
Verify that an array of products is returned in the response body.
if (!product) {
return res.status(404).send('Product not found');
}
return res.status(200).send(product);
}
productRouter.get('/:id', controller.getOneProduct);
Filter Products
● The goal is to implement an API to filter products in an e-commerce
application.
● The filter criteria include minimum price, maximum price, and category.
● The filter function is added to the product model as a static function.
● The filter function uses the JavaScript filter method to filter products based on
the given criteria.
● The filter function receives minimum price, maximum price, and category as
parameters.
● The filtered products are stored in the 'result' constant and returned.
● The filter function is called from the controller.
● The filter products method is added to the controller to handle the filter API
request.
● Query parameters are used to pass the filter criteria from the client to the
server.
● The filter API route is created using a GET request and the '/filter' path.
● The filter API route calls the filter products method in the controller.
● The filter criteria are retrieved from the query object using request.query.
● The filter criteria are passed to the filter function in the product model.
● The filtered data is sent back to the client as a response with a status of 200
(OK).
● Users can specify the filter criteria as query parameters in the API URL.
Note: The code snippets assume the existence of a product model named
"Product" and an array of products named "products". The syntax +minPrice
is used to convert the query parameter value from string to a number.
Summarising it
Let’s summarise what we have learned in this module:
1. Explored difficulties encountered with MVC architecture.
2. Acquired knowledge about various types of APIs and their functionalities.
3. Gained insights into REST APIs and their practical uses.
4. Commenced the development of an E-Commerce API project.
5. Established a well-organized folder structure for the project.
6. Familiarized oneself with Express Router and established product routes for
the project.
7. Designed the product model for the API project.
8. Successfully incorporated APIs for adding products, retrieving individual
products, and filtering products.
● Express routing