Building and Consuming RESTful APIs with Express and MongoDB Technology by Erick Lima Azevedo - October 23, 2024October 24, 20240 Introduction Building a RESTful API is a crucial skill for full stack developers. Express, a minimal and flexible Node.js web application framework, combined with MongoDB, a NoSQL database, provides a powerful foundation for building efficient and scalable APIs. RESTful APIs constitute an important topic covered in career-oriented technical courses for full-stack developers, such as a full stack developer course in Bangalore and such cities. This article will walk you through the process of building and consuming RESTful APIs with Express and MongoDB. Prerequisites Before you proceed with the task of building and consuming RESTful APIs with Express and MongoDB, ensure that you have the following basic prerequisites: Basic knowledge of JavaScript and Node.js Installed versions of Node.js, npm, and MongoDB Step-by-Step Procedure The following sections describe the process for building and consuming RESTful APIs with Express and MongoDB in the same sequence as would be covered in a standard technical course for full-stack developers, for instance, a full stack developer course in Bangalore. Step 1: Setting Up the Project Create a New Project: bash Copy code mkdir express-mongodb-api cd express-mongodb-api npm init -y Install Dependencies: bash Copy code npm install express mongoose body-parser cors express: Web framework mongoose: ODM (Object Data Modeling) for MongoDB body-parser: Parse incoming request bodies cors: Enable Cross-Origin Resource Sharing Step 2: Setting Up Express and MongoDB Connection Create the Main Application File index.js: javascript Copy code const express = require(‘express’); const mongoose = require(‘mongoose’); const bodyParser = require(‘body-parser’); const cors = require(‘cors’); const app = express(); // Middleware app.use(bodyParser.json()); app.use(cors()); // Connect to MongoDB mongoose.connect(‘mongodb://localhost:27017/expressapi’, { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log(‘MongoDB Connected’)) .catch((err) => console.error(‘MongoDB connection error:’, err)); // Start the server const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); Step 3: Creating a Mongoose Schema and Model Create a models directory and a file User.js: javascript Copy code const mongoose = require(‘mongoose’); const UserSchema = new mongoose.Schema({ name: { type: String, required: true, }, email: { type: String, required: true, unique: true, }, age: { type: Number, required: true, }, }); module.exports = mongoose.model(‘User’, UserSchema); Step 4: Building RESTful API Routes Create a routes directory and a file users.js: javascript Copy code const express = require(‘express’); const router = express.Router(); const User = require(‘../models/User’); // Create a new user router.post(‘/’, async (req, res) => { try { const user = new User(req.body); const savedUser = await user.save(); res.status(201).json(savedUser); } catch (error) { res.status(400).json({ error: error.message }); } }); // Get all users router.get(‘/’, async (req, res) => { try { const users = await User.find(); res.json(users); } catch (error) { res.status(500).json({ error: error.message }); } }); // Get a user by ID router.get(‘/:id’, async (req, res) => { try { const user = await User.findById(req.params.id); if (!user) return res.status(404).json({ message: ‘User not found’ }); res.json(user); } catch (error) { res.status(500).json({ error: error.message }); } }); // Update a user by ID router.put(‘/:id’, async (req, res) => { try { const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true }); if (!updatedUser) return res.status(404).json({ message: ‘User not found’ }); res.json(updatedUser); } catch (error) { res.status(400).json({ error: error.message }); } }); // Delete a user by ID router.delete(‘/:id’, async (req, res) => { try { const deletedUser = await User.findByIdAndDelete(req.params.id); if (!deletedUser) return res.status(404).json({ message: ‘User not found’ }); res.json({ message: ‘User deleted’ }); } catch (error) { res.status(500).json({ error: error.message }); } }); module.exports = router; Connect the Routes in index.js: javascript Copy code const usersRoute = require(‘./routes/users’); app.use(‘/api/users’, usersRoute); Step 5: Testing the API You can test your API using tools like Postman or cURL: POST Request to http://localhost:5000/api/users with JSON body: json Copy code { “name”: “John Doe”, “email”: “john@example.com”, “age”: 30 } GET Request to http://localhost:5000/api/users to retrieve all users. GET Request to http://localhost:5000/api/users/:id to retrieve a specific user by ID. PUT Request to http://localhost:5000/api/users/:id to update a user’s details. DELETE Request to http://localhost:5000/api/users/:id to delete a user by ID. Consuming the RESTful API in a Front-End Application To consume the RESTful API, you can use the fetch API or a library like Axios in your front-end application. Example using fetch: javascript Copy code fetch(‘http://localhost:5000/api/users’) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(‘Error:’, error)); Example using axios: javascript Copy code import axios from ‘axios’; axios.get(‘http://localhost:5000/api/users’) .then(response => console.log(response.data)) .catch(error => console.error(‘Error:’, error)); Best Practices Here are some best practice tips for building and consuming RESTful APIs with Express and MongoDB. Any inclusive full stack Java developer training will ensure that learners are made aware of and will encourage them to observe in their professional practice. Structuring Your Project Follow MVC Architecture: Separate your code into Models, Views, and Controllers to maintain a clean and organised structure. Use Environment Variables: Store sensitive data such as database URIs, API keys, and secret tokens in environment variables using a .env file. Use the dotenv package to manage them. Error Handling and Logging Centralise Error Handling: Implement global error-handling middleware to manage errors efficiently. This approach ensures consistent error responses across your API. Use Logging Libraries: Use libraries like winston or morgan to log incoming requests and errors for debugging and monitoring. Security Best Practices Enable CORS Carefully: Use the Cors middleware but configure it to allow only specific origins rather than allowing access to everyone. Sanitise User Input: Prevent SQL injection and NoSQL injection attacks by using input sanitisation libraries like express-validator or validator. Implement Rate Limiting: Use express-rate limit to prevent abuse and brute force attacks. Use HTTPS: Ensure your API is served over HTTPS, especially in production, to encrypt data in transit. Data Validation and Schema Design Use Mongoose Validation: Leverage Mongoose’s built-in validation to enforce data integrity at the schema level. Validate Incoming Requests: Use libraries like Joi or express-validator to validate incoming request data at the API level. API Versioning Implement API Versioning: Maintain backward compatibility by versioning your API endpoints (for example, /api/v1/users). Deprecate Carefully: Communicate version deprecation in advance to allow clients time to adjust. Performance Optimisation Implement Caching: Use caching mechanisms like Redis to cache frequently accessed data and reduce database load. Compress Responses: Use the compression middleware to reduce response sizes, improving API performance. Use Connection Pooling: Manage MongoDB connections efficiently by using connection pooling to reduce the overhead of creating new connections. Following these best practices will help you build secure, scalable, and efficient RESTful APIs with Express and MongoDB. Implementing these tips not only enhances the performance of your API but also makes it easier to maintain, debug, and scale as your application grows. Most experienced full-stack developers and those who have the learning from a career-oriented full stack Java developer training program will adhere to such useful best practice tips to work faster and smarter. Conclusion This article explained how you can build and consume a RESTful API using Express and MongoDB. This setup can be expanded with additional features, such as authentication, validation, or integration with other services, making it a solid foundation for building full-stack applications. Enroll in an advanced full stack Java developer training course to further your learning to perform more complex tasks and excel in your professional role. Name: ExcelR – Business Analyst, Full Stack Development, Tableau & Power BI Course Training Address: 10, 3rd floor, Safeway Plaza, 27th Main Rd, Old Madiwala, Jay Bheema Nagar, 1st Stage, BTM 1st Stage, Bengaluru, Karnataka 560068 Phone: 07353006061 Business Email:enquiry@excelr.com