Rest API - Express Service Boilerplate
A RESTful API built with Node.js, Express, and MongoDB Atlas for managing user data. This project demonstrates modern API development practices with proper validation, error handling, and cloud deployment.
Live API: https://api.vineetkr.com
📚 Table of Contents
- Technology Stack
- What is Express.js?
- Project Features
- Project Structure
- API Endpoints
- Getting Started
- Environment Variables
- Deployment
- Security
- Contributing
🛠️ Technology Stack
Backend Framework- Node.js (v18+)
- Express.js (v4.18.2)
- MongoDB Atlas
- Mongoose (v8.0.3)
- Nodemon (v3.0.2)
- GitHub Actions
🚀 What is Express.js?
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It's the de facto standard server framework for Node.js.
Why Express.js?- Fast & Lightweight - Minimal overhead with high performance
- Easy to Learn - Simple, intuitive API design
- Middleware Support - Extensible through middleware functions
- Robust Routing - Powerful routing mechanism for handling HTTP requests
- Large Ecosystem - Thousands of npm packages compatible with Express
// 1. Import Express
import express from "express";
const app = express();
// 2. Define Routes (API Endpoints)
app.get("/api/users", (req, res) => {
res.json({ message: "Get all users" });
});
app.post("/api/users", (req, res) => {
res.json({ message: "Create user" });
});
// 3. Start Server
app.listen(3000, () => {
console.log("API running on port 3000");
});
Key Concepts:
- Routes - URL paths that handle specific HTTP methods (GET, POST, PUT, DELETE)
- Middleware - Functions that process requests before reaching route handlers
- Request/Response - Objects containing HTTP request data and methods to send responses
- JSON Support - Built-in parsing and sending of JSON data
✨ Project Features
- ✅ RESTful API Design - Follows REST principles for resource management
- ✅ CRUD Operations - Create, Read, Update operations for user data
- ✅ Input Validation - Schema validation using Zod
- ✅ Error Handling - Centralized error handling middleware
- ✅ MongoDB Integration - Cloud database with Mongoose ODM
- ✅ Environment Configuration - Secure secret management
- ✅ CORS Support - Cross-origin requests enabled
- ✅ Serverless Deployment - Auto-scaling on Vercel
- ✅ CI/CD Pipeline - Automated deployment with GitHub Actions
- ✅ Production Ready - Optimized for serverless environments
📁 Project Structure
vineetkr-api/
├── src/
│ ├── server.js # Express app setup & entry point
│ ├── config/
│ │ └── database.js # MongoDB connection config
│ ├── controllers/
│ │ └── userController.js # Business logic for user operations
│ ├── models/
│ │ └── User.js # Mongoose schema & model
│ ├── routes/
│ │ └── userRoutes.js # API route definitions
│ └── validators/
│ └── userValidator.js # Zod validation schemas
├── .github/
│ └── workflows/
│ └── deploy.yml # GitHub Actions CI/CD
├── .env # Local environment variables (gitignored)
├── .env.example # Template for environment variables
├── .gitignore # Git ignore rules
├── vercel.json # Vercel deployment config
├── package.json # Dependencies & scripts
└── README.md # This file
Architecture Flow
Request → Express Middleware → Router → Controller → Model → Database
↓
Response ← JSON Response ← Controller ← Model ← Database Query
🔌 API Endpoints
Base URL: https://api.vineetkr.com
GET /api/users
Response:
{
"success": true,
"count": 2,
"data": [
{
"_id": "507f1f77bcf86cd799439011",
"name": "Vineet Kumar",
"email": "vineet@vineetkr.com",
"age": 25,
"createdAt": "2025-12-25T10:30:00.000Z",
"updatedAt": "2025-12-25T10:30:00.000Z"
}
]
}
Get Single User
GET /api/users?id=507f1f77bcf86cd799439011
Create User
POST /api/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
Response:
{
"success": true,
"message": "User created successfully",
"data": {
"_id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
}
Update User
PUT /api/users/:id
Content-Type: application/json
{
"name": "Jane Doe",
"age": 32
}
🏁 Getting Started
Prerequisites- Node.js v18 or higher (Download)
- npm or yarn package manager
- MongoDB Atlas Account (Sign up)
- Git (Download)
- Clone the repository
git clone https://github.com/contactkrvineet/vineetkr-api.git cd vineetkr-api - Install dependencies
npm install - Set up environment variables
# Copy example file cp .env.example .env # Edit .env and add your credentials nano .env - Configure MongoDB Atlas
- Create a cluster at MongoDB Atlas
- Get your connection string:
- Click Connect → Connect your application
- Copy the connection string
- Update Network Access:
- Go to Network Access → Add IP Address
- Allow access from anywhere:
0.0.0.0/0(for development)
- Update .env file
PORT=3000 MONGODB_URI=mongodb+srv://credluster0.xxxxx.mongodb.net/your_database NODE_ENV=development ALLOWED_ORIGINS=http://localhost:3000
- Development mode (with auto-restart):
npm run dev - Production mode:
npm start
The API will be running at: http://localhost:3000
Testing the API- Using cURL:
# Get all users curl http://localhost:3000/api/users # Create a user curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"name": "Test User", "email": "test@example.com", "age": 25}' - Using Browser:
Open http://localhost:3000 to see the welcome message - Using Postman:
- Import the API endpoints
- Set base URL to
http://localhost:3000 - Test GET, POST, PUT operations
🔐 Environment Variables
Required Variables| Variable | Description | Example |
|---|---|---|
| PORT | Server port number | 3000 |
| MONGODB_URI | MongoDB connection string | mongodb+srv://@cluster.mongodb.net/db |
| NODE_ENV | Environment mode | development or production |
| ALLOWED_ORIGINS | CORS allowed origins (comma-separated) | https://vineetkr.com,http://localhost:3000 |
PORT=3000
MONGODB_URI=mongodb+srv://@cluster.mongodb.net/database
NODE_ENV=development
ALLOWED_ORIGINS=http://localhost:3000
Production (Vercel)
- Go to Project Settings → Environment Variables
- Add each variable with production values
- Redeploy the application
🚢 Deployment
Deploy to Vercel- Install Vercel CLI
npm install -g vercel - Login to Vercel
vercel login - Deploy
vercel --prod - Set Environment Variables
- Go to Vercel dashboard
- Navigate to Settings → Environment Variables
- Add all required variables
- Redeploy
This project includes a GitHub Actions workflow that automatically deploys to Vercel on every push to
main or prac branch.
- Add secrets to GitHub repository:
- VERCEL_TOKEN - Get from vercel.com/account/tokens
- VERCEL_ORG_ID - Found in
.vercel/project.json - VERCEL_PROJECT_ID - Found in
.vercel/project.json
- Push to
mainorpracbranch - deployment happens automatically!
🔒 Security
Best Practices Implemented- ✅ Environment Variables - Secrets stored securely, never in code
- ✅ Input Validation - All inputs validated with Zod schemas
- ✅ CORS Configuration - Controlled cross-origin access
- ✅ Error Handling - No sensitive data leaked in error responses
- ✅ MongoDB Atlas - Database hosted securely in the cloud
- ✅ .gitignore - Sensitive files excluded from version control
- MongoDB Atlas Network Access configured
- Strong database password used
- Environment variables set in hosting platform
- CORS origins restricted in production
- HTTPS enabled (automatic with Vercel)
- .env file never committed to git
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📝 License
This project is licensed under the Vineetkr License.
👨💻 Author
Vineet Kumar
Website: vineetkr.com
GitHub: @contactkrvineet
📞 Support
- Open an Issue
- Email: contactkrvineet@gmail.com, vineet@vineetkr.com
🎓 Learning Resources
- Express.js Documentation
- MongoDB Docs
- Mongoose Guide
- Zod Documentation
- REST API Design Best Practices
- Node.js Best Practices
Happy Coding! 🚀