v2/examples/05-swarm-apps/rest-api-advanced/docs/API.md
The Advanced REST API is a production-ready e-commerce API built with Node.js, Express, and MongoDB. It features:
Development: http://localhost:3000/api
Production: https://api.example.com/api
Current version: 1.0.0
npm install.env.example)npm run seednpm run dev# Server Configuration
PORT=3000
NODE_ENV=development
API_URL=http://localhost:3000
# Database
MONGODB_URI=mongodb://localhost:27017/rest-api-advanced
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
# JWT
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRE=7d
JWT_REFRESH_EXPIRE=30d
ROTATE_REFRESH_TOKENS=true
# Security
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001
BCRYPT_ROUNDS=10
# Email (for production)
EMAIL_HOST=smtp.example.com
EMAIL_PORT=587
[email protected]
EMAIL_PASS=your-email-password
[email protected]
The API uses JWT (JSON Web Tokens) for authentication with support for refresh tokens.
Include the JWT token in the Authorization header:
Authorization: Bearer <your-jwt-token>
The API implements rate limiting to prevent abuse:
X-RateLimit-Limit: Total requests allowedX-RateLimit-Remaining: Requests remainingX-RateLimit-Reset: Reset timestampWhen rate limit is exceeded:
{
"success": false,
"message": "Too many requests from this IP, please try again later.",
"error": {
"statusCode": 429,
"message": "Rate limit exceeded"
}
}
The API uses consistent error responses across all endpoints.
{
"success": false,
"message": "Human-readable error message",
"error": {
"statusCode": 400,
"message": "Detailed error description"
}
}
{
"errors": [
{
"field": "email",
"message": "Invalid email format"
},
{
"field": "password",
"message": "Password must be at least 6 characters"
}
]
}
400 - Bad Request (validation errors)401 - Unauthorized (missing/invalid token)403 - Forbidden (insufficient permissions)404 - Not Found409 - Conflict (duplicate resource)429 - Too Many Requests (rate limit)500 - Internal Server ErrorPOST /api/auth/register
Create a new user account.
Request Body:
{
"email": "[email protected]",
"password": "SecurePass123!",
"name": "John Doe"
}
Response (201):
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "507f1f77bcf86cd799439011",
"email": "[email protected]",
"name": "John Doe",
"role": "user",
"isEmailVerified": false,
"createdAt": "2024-01-01T00:00:00.000Z"
}
}
POST /api/auth/login
Authenticate user and receive tokens.
Request Body:
{
"email": "[email protected]",
"password": "SecurePass123!"
}
Response (200):
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "507f1f77bcf86cd799439011",
"email": "[email protected]",
"name": "John Doe",
"role": "user",
"lastLogin": "2024-01-01T00:00:00.000Z"
}
}
POST /api/auth/refresh
Get new access token using refresh token.
Request Body:
{
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
Response (200):
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
POST /api/auth/logout
Logout and blacklist current token.
Headers:
Authorization: Bearer <token>
Response (200):
{
"success": true,
"message": "Logged out successfully"
}
GET /api/auth/me
Get authenticated user details.
Headers:
Authorization: Bearer <token>
Response (200):
{
"success": true,
"data": {
"user": {
"id": "507f1f77bcf86cd799439011",
"email": "[email protected]",
"name": "John Doe",
"role": "user",
"isEmailVerified": true,
"createdAt": "2024-01-01T00:00:00.000Z"
}
}
}
POST /api/auth/forgot-password
Request password reset email.
Request Body:
{
"email": "[email protected]"
}
Response (200):
{
"success": true,
"message": "Password reset email sent"
}
POST /api/auth/reset-password
Reset password using token from email.
Request Body:
{
"token": "reset-token-from-email",
"password": "NewSecurePass123!"
}
Response (200):
{
"success": true,
"message": "Password reset successful"
}
GET /api/auth/verify-email/:token
Verify email address using token from email.
Response (200):
{
"success": true,
"message": "Email verified successfully"
}
POST /api/auth/check-password
Check password strength without creating account.
Request Body:
{
"password": "MyStr0ng!Pass"
}
Response (200):
{
"success": true,
"data": {
"strength": {
"isValid": true,
"score": 5,
"level": "strong",
"feedback": []
}
}
}
GET /api/products
Get paginated list of products with filtering and sorting.
Query Parameters:
page (default: 1) - Page numberlimit (default: 20) - Items per pagesearch - Search by name or descriptioncategory - Filter by categoryminPrice - Minimum price filtermaxPrice - Maximum price filtersort - Sort field (price, -price, name, -name, createdAt, -createdAt)inStock - Filter by stock availability (true/false)Response (200):
{
"success": true,
"data": [
{
"id": "507f1f77bcf86cd799439011",
"name": "Laptop",
"description": "High-performance laptop",
"price": 999.99,
"category": "Electronics",
"sku": "LAP001",
"stock": 10,
"images": ["https://example.com/image1.jpg"],
"tags": ["new", "featured"],
"averageRating": 4.5,
"reviewCount": 25,
"isActive": true,
"createdAt": "2024-01-01T00:00:00.000Z"
}
],
"meta": {
"total": 100,
"page": 1,
"limit": 20,
"totalPages": 5,
"hasNextPage": true,
"hasPrevPage": false
}
}
GET /api/products/:id
Get detailed product information.
Response (200):
{
"success": true,
"data": {
"id": "507f1f77bcf86cd799439011",
"name": "Laptop",
"description": "High-performance laptop with latest specs",
"price": 999.99,
"category": "Electronics",
"sku": "LAP001",
"stock": 10,
"images": [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg"
],
"tags": ["new", "featured"],
"specifications": {
"brand": "TechBrand",
"model": "TB-2024",
"weight": "1.5kg",
"dimensions": "35x25x2cm"
},
"reviews": [
{
"id": "507f1f77bcf86cd799439012",
"user": "507f1f77bcf86cd799439013",
"rating": 5,
"title": "Excellent product!",
"comment": "Very satisfied with this laptop.",
"helpfulCount": 10,
"createdAt": "2024-01-02T00:00:00.000Z"
}
],
"averageRating": 4.5,
"reviewCount": 25,
"isActive": true,
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
}
POST /api/products
Create a new product.
Headers:
Authorization: Bearer <admin-token>
Request Body:
{
"name": "New Product",
"description": "Product description",
"price": 149.99,
"category": "Electronics",
"sku": "NEW001",
"stock": 20,
"tags": ["new"],
"specifications": {
"weight": "500g",
"dimensions": "10x10x5cm"
}
}
Response (201):
{
"success": true,
"data": {
"id": "507f1f77bcf86cd799439014",
"name": "New Product",
"price": 149.99,
"category": "Electronics",
"sku": "NEW001",
"stock": 20,
"createdAt": "2024-01-01T00:00:00.000Z"
}
}
PUT /api/products/:id
Update product details.
Headers:
Authorization: Bearer <admin-token>
Request Body:
{
"name": "Updated Product Name",
"price": 129.99,
"stock": 15
}
Response (200):
{
"success": true,
"data": {
"id": "507f1f77bcf86cd799439011",
"name": "Updated Product Name",
"price": 129.99,
"stock": 15,
"updatedAt": "2024-01-01T00:00:00.000Z"
}
}
DELETE /api/products/:id
Delete a product.
Headers:
Authorization: Bearer <admin-token>
Response (200):
{
"success": true,
"message": "Product deleted successfully"
}
POST /api/products/:id/reviews
Add a review to a product.
Headers:
Authorization: Bearer <token>
Request Body:
{
"rating": 5,
"title": "Excellent product!",
"comment": "Very satisfied with this purchase."
}
Response (201):
{
"success": true,
"data": {
"reviews": [
{
"id": "507f1f77bcf86cd799439015",
"user": "507f1f77bcf86cd799439013",
"rating": 5,
"title": "Excellent product!",
"comment": "Very satisfied with this purchase.",
"createdAt": "2024-01-01T00:00:00.000Z"
}
],
"averageRating": 5,
"reviewCount": 1
}
}
PUT /api/products/:id/inventory
Update product inventory.
Headers:
Authorization: Bearer <admin-token>
Request Body:
{
"stock": 50,
"operation": "set" // "set", "increment", "decrement"
}
Response (200):
{
"success": true,
"data": {
"id": "507f1f77bcf86cd799439011",
"stock": 50,
"lastStockUpdate": "2024-01-01T00:00:00.000Z"
}
}
POST /api/orders
Create a new order.
Headers:
Authorization: Bearer <token>
Request Body:
{
"items": [
{
"product": "507f1f77bcf86cd799439011",
"quantity": 2
}
],
"shippingAddress": {
"name": "John Doe",
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "USA"
},
"paymentMethod": "credit_card",
"notes": "Please deliver between 9 AM - 5 PM"
}
Response (201):
{
"success": true,
"data": {
"id": "507f1f77bcf86cd799439016",
"orderNumber": "ORD-2024-0001",
"items": [
{
"product": "507f1f77bcf86cd799439011",
"quantity": 2,
"price": 99.99,
"subtotal": 199.98
}
],
"subtotal": 199.98,
"tax": 20.00,
"shipping": 10.00,
"totalAmount": 229.98,
"status": "pending",
"paymentStatus": "pending",
"createdAt": "2024-01-01T00:00:00.000Z"
}
}
GET /api/orders
Get authenticated user's orders.
Headers:
Authorization: Bearer <token>
Query Parameters:
page (default: 1)limit (default: 20)status - Filter by order statussort - Sort ordersResponse (200):
{
"success": true,
"data": [
{
"id": "507f1f77bcf86cd799439016",
"orderNumber": "ORD-2024-0001",
"totalAmount": 229.98,
"status": "pending",
"paymentStatus": "completed",
"createdAt": "2024-01-01T00:00:00.000Z"
}
],
"meta": {
"total": 10,
"page": 1,
"limit": 20,
"totalPages": 1
}
}
GET /api/orders/:id
Get detailed order information.
Headers:
Authorization: Bearer <token>
Response (200):
{
"success": true,
"data": {
"id": "507f1f77bcf86cd799439016",
"orderNumber": "ORD-2024-0001",
"user": {
"id": "507f1f77bcf86cd799439013",
"name": "John Doe",
"email": "[email protected]"
},
"items": [
{
"product": {
"id": "507f1f77bcf86cd799439011",
"name": "Laptop",
"price": 99.99
},
"quantity": 2,
"price": 99.99,
"subtotal": 199.98
}
],
"subtotal": 199.98,
"tax": 20.00,
"shipping": 10.00,
"totalAmount": 229.98,
"status": "pending",
"paymentStatus": "completed",
"paymentMethod": "credit_card",
"shippingAddress": {
"name": "John Doe",
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "USA"
},
"tracking": null,
"statusHistory": [
{
"status": "pending",
"timestamp": "2024-01-01T00:00:00.000Z"
}
],
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z"
}
}
DELETE /api/orders/:id
Cancel an order (only pending/processing orders).
Headers:
Authorization: Bearer <token>
Response (200):
{
"success": true,
"message": "Order cancelled successfully"
}
PUT /api/orders/:id/status
Update order status.
Headers:
Authorization: Bearer <admin-token>
Request Body:
{
"status": "processing" // "pending", "processing", "shipped", "delivered", "cancelled"
}
Response (200):
{
"success": true,
"data": {
"id": "507f1f77bcf86cd799439016",
"status": "processing",
"statusHistory": [
{
"status": "pending",
"timestamp": "2024-01-01T00:00:00.000Z"
},
{
"status": "processing",
"timestamp": "2024-01-01T01:00:00.000Z",
"updatedBy": "507f1f77bcf86cd799439017"
}
]
}
}
POST /api/orders/:id/tracking
Add shipping tracking information.
Headers:
Authorization: Bearer <admin-token>
Request Body:
{
"carrier": "FedEx",
"trackingNumber": "1234567890",
"estimatedDelivery": "2024-01-20"
}
Response (200):
{
"success": true,
"data": {
"tracking": {
"carrier": "FedEx",
"trackingNumber": "1234567890",
"estimatedDelivery": "2024-01-20"
}
}
}
GET /api/health
Basic health check.
Response (200):
{
"status": "healthy",
"timestamp": "2024-01-01T00:00:00.000Z",
"uptime": 3600,
"environment": "development"
}
GET /api/health/ready
Check if all services are ready.
Response (200):
{
"status": "ready",
"checks": {
"database": "connected",
"redis": "connected"
}
}
GET /api/health/live
Check if the service is alive.
Response (200):
{
"status": "alive",
"timestamp": "2024-01-01T00:00:00.000Z"
}
{
_id: ObjectId,
email: String (unique, required),
password: String (hashed, required),
name: String (required),
role: String (enum: ['user', 'admin'], default: 'user'),
isActive: Boolean (default: true),
isEmailVerified: Boolean (default: false),
emailVerificationToken: String,
passwordResetToken: String,
passwordResetExpires: Date,
loginAttempts: Number (default: 0),
lockUntil: Date,
lastLogin: Date,
createdAt: Date,
updatedAt: Date
}
{
_id: ObjectId,
name: String (required),
description: String,
price: Number (required, min: 0),
category: String (required),
sku: String (unique, required),
stock: Number (default: 0, min: 0),
images: [String],
tags: [String],
specifications: Object,
reviews: [{
user: ObjectId (ref: 'User'),
rating: Number (1-5),
title: String,
comment: String,
helpfulCount: Number (default: 0),
createdAt: Date
}],
averageRating: Number (default: 0),
reviewCount: Number (default: 0),
isActive: Boolean (default: true),
createdAt: Date,
updatedAt: Date
}
{
_id: ObjectId,
orderNumber: String (unique, required),
user: ObjectId (ref: 'User', required),
items: [{
product: ObjectId (ref: 'Product'),
quantity: Number (min: 1),
price: Number,
subtotal: Number
}],
subtotal: Number (required),
tax: Number (default: 0),
shipping: Number (default: 0),
totalAmount: Number (required),
status: String (enum: ['pending', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded']),
paymentStatus: String (enum: ['pending', 'completed', 'failed', 'refunded']),
paymentMethod: String (enum: ['credit_card', 'debit_card', 'paypal', 'stripe']),
paymentDetails: Object,
shippingAddress: {
name: String,
street: String,
city: String,
state: String,
zipCode: String,
country: String
},
tracking: {
carrier: String,
trackingNumber: String,
estimatedDelivery: Date
},
notes: String,
statusHistory: [{
status: String,
timestamp: Date,
updatedBy: ObjectId (ref: 'User')
}],
refunds: [{
amount: Number,
reason: String,
processedAt: Date,
processedBy: ObjectId (ref: 'User')
}],
createdAt: Date,
updatedAt: Date
}
Browse Products
GET /api/products?category=Electronics&sort=-rating
View Product Details
GET /api/products/507f1f77bcf86cd799439011
Register/Login
POST /api/auth/register
{
"email": "[email protected]",
"password": "SecurePass123!",
"name": "John Doe"
}
Add Review (optional)
POST /api/products/507f1f77bcf86cd799439011/reviews
{
"rating": 5,
"comment": "Great product!"
}
Create Order
POST /api/orders
{
"items": [
{
"product": "507f1f77bcf86cd799439011",
"quantity": 1
}
],
"shippingAddress": {
"name": "John Doe",
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "USA"
},
"paymentMethod": "credit_card"
}
Track Order
GET /api/orders/507f1f77bcf86cd799439016
Login as Admin
POST /api/auth/login
{
"email": "[email protected]",
"password": "AdminPass123!"
}
Create Product
POST /api/products
{
"name": "New Laptop",
"description": "Latest model laptop",
"price": 1299.99,
"category": "Electronics",
"sku": "LAP002",
"stock": 25
}
Update Inventory
PUT /api/products/507f1f77bcf86cd799439011/inventory
{
"stock": 50,
"operation": "set"
}
Process Orders
GET /api/orders/admin/all?status=pending
PUT /api/orders/507f1f77bcf86cd799439016/status
{
"status": "processing"
}
POST /api/orders/507f1f77bcf86cd799439016/tracking
{
"carrier": "FedEx",
"trackingNumber": "1234567890"
}
For API support, please contact: