A comprehensive CRUD API for inventory management using MongoDB, Express, and Node.js.
- RESTful API for managing products and suppliers
- MVC architecture with model, controller, and route separation
- Two MongoDB collections with rich data models
- Comprehensive validation using both:
- Express-validator for request data validation
- Custom model-level validation methods
- Error handling for all routes
- API documentation with Swagger
├── server.js # Main application entry point
├── db.js # Database connection module
├── swagger.js # Swagger definition and generation script
├── generate-swagger.js # Script to generate swagger.json
├── controllers/ # Controller functions
│ ├── productController.js
│ └── supplierController.js
├── models/ # Data models with validation
│ ├── Product.js
│ └── Supplier.js
├── middleware/ # Middleware functions
│ └── validation.js # Request validation rules
├── routes/ # API route definitions
│ ├── products.js
│ └── suppliers.js
└── swagger.json # Generated API documentation
- Node.js (v14 or higher)
- MongoDB (local or Atlas)
- Clone the repository:
git clone <repository-url>
cd crud-api-project- Install dependencies:
npm install- Create a
.envfile in the root directory with the following variables:
MONGODB_URI=mongodb://localhost:27017/product-api
PORT=3000
Start the server:
npm startFor development with auto-restart on file changes:
npm run devAfter making changes to the API, you should update the Swagger documentation:
npm run swaggerThis will generate an updated swagger.json file based on the definitions in swagger.js.
Once the server is running, you can access the Swagger documentation at:
http://localhost:3000/api-docs
GET /api/products- Get all productsGET /api/products/:id- Get a specific productPOST /api/products- Create a new productPUT /api/products/:id- Update a productDELETE /api/products/:id- Delete a productGET /api/products/supplier/:supplierId- Get products from a specific supplier
GET /api/suppliers- Get all suppliersGET /api/suppliers/:id- Get a specific supplierPOST /api/suppliers- Create a new supplierPUT /api/suppliers/:id- Update a supplierDELETE /api/suppliers/:id- Delete a supplier
{
"name": "String (required)",
"description": "String (required)",
"price": "Number (required)",
"discountPercentage": "Number (optional)",
"stock": "Integer (required)",
"category": "String (required)",
"tags": ["String"],
"dimensions": {
"height": "Number",
"width": "Number",
"depth": "Number",
"unit": "String"
},
"weight": "Number",
"supplierId": "MongoDB ObjectId (reference to Supplier)",
"isAvailable": "Boolean (required)",
"imageUrl": "String (URL)",
"createdAt": "Date"
}{
"name": "String (required)",
"contactName": "String (required)",
"email": "String (required)",
"phone": "String (required)",
"address": {
"street": "String (required)",
"city": "String (required)",
"state": "String (required)",
"zipCode": "String (required)"
},
"country": "String (required)",
"supplierType": "String enum [manufacturer, wholesaler, distributor, retailer] (required)",
"paymentTerms": "String (required)",
"isActive": "Boolean (required)",
"createdAt": "Date"
}The API implements two levels of validation:
-
Request Validation: Using express-validator in middleware/validation.js
- Ensures incoming requests have correct data types and required fields
- Provides detailed error messages for bad requests
-
Model Validation: Using custom validate methods in models
- Performs deeper validation logic specific to each model
- Handles business rules and constraints
All routes implement consistent error handling with appropriate HTTP status codes:
- 400: Bad Request (validation errors, invalid IDs)
- 404: Not Found (item doesn't exist)
- 500: Server Error (database errors, unexpected issues)
This application can be deployed to various cloud platforms:
- Create a Heroku account and install the Heroku CLI
- Login to Heroku:
heroku login
- Create a new Heroku app:
heroku create your-app-name
- Set environment variables:
heroku config:set MONGODB_URI=your_mongodb_atlas_connection_string
- Push your code to Heroku:
git push heroku main
- Create a Render account
- From the Render dashboard, click "New" and select "Web Service"
- Connect your GitHub repository or deploy from a public repository URL
- Configure the web service:
- Name: Choose a name for your service (e.g., "inventory-management-api")
- Environment: Node
- Region: Choose the closest region to your users
- Branch: main (or your preferred branch)
- Build Command:
npm install && npm run swagger - Start Command:
node server.js - Plan: Free (or select a paid plan for production use)
- Add the following environment variables:
MONGODB_URI: Your MongoDB Atlas connection stringNODE_ENV: productionPORT: 10000 (Render internally uses this)APP_URL: Your Render app URL once deployed (e.g., https://inventory-management-api.onrender.com)
- Click "Create Web Service"
This repository includes a render.yaml file for easier deployment:
- Fork this repository on GitHub
- Go to the Render Dashboard
- Click on the "New" button and select "Blueprint" from the dropdown
- Connect your forked GitHub repository
- Render will detect the
render.yamlfile and set up the service - You'll still need to manually configure the
MONGODB_URIenvironment variable in the Render dashboard
- The free tier of Render will spin down your web service after 15 minutes of inactivity
- The first request after inactivity will take a bit longer as the service spins back up
- For production use, consider upgrading to a paid plan
- If you need to seed your database, run
npm run seedlocally before deploying, or set up a one-time service in Render to run the seed script
- Create a Railway account
- Create a new project and link your GitHub repository
- Add your environment variables in the Railway dashboard
- Deploy your application
The following environment variables are required:
MONGODB_URI: Your MongoDB Atlas connection stringPORT: The port number (optional, defaults to 3000)
Make sure to keep these environment variables secure and never commit them to your repository.
ISC