Development Manual - Adding Features - Documentation

← Back to Docs Raw Markdown JSON API

Development Manual - Adding Features

Complete guide for extending your Node.js Multi-API application at api.app.lobott.com

📡 Adding New API Endpoints

1. Add to API Routes

Edit routes/api.js to add new endpoints:

// Example: Adding a new products API
router.get('/products', (req, res) => {
  const { category, limit } = req.query;
  let filteredProducts = products; // Your data source
  
  if (category) {
    filteredProducts = products.filter(p => p.category === category);
  }
  
  if (limit) {
    filteredProducts = filteredProducts.slice(0, parseInt(limit));
  }
  
  res.json({
    success: true,
    count: filteredProducts.length,
    data: filteredProducts
  });
});

router.get('/products/:id', (req, res) => {
  const product = products.find(p => p.id === parseInt(req.params.id));
  if (!product) {
    return res.status(404).json({ 
      success: false, 
      message: 'Product not found' 
    });
  }
  res.json({ success: true, data: product });
});

2. Update API Overview

Update the main API endpoint in routes/api.js:

router.get('/', (req, res) => {
  res.json({
    message: 'Multi-API Server',
    version: '1.0.0',
    endpoints: {
      users: '/api/users',
      posts: '/api/posts',
      search: '/api/search',
      time: '/api/time',
      products: '/api/products'  // Add your new endpoint
    },
    documentation: '/docs'
  });
});

3. Update API Explorer

Edit routes/pages.js in the /api-explorer route:

{
  method: 'GET',
  path: '/api/products',
  description: 'Get all products (supports ?category and ?limit parameters)',
  example: '/api/products?category=electronics&limit=5'
},
{
  method: 'GET',
  path: '/api/products/:id',
  description: 'Get specific product by ID',
  example: '/api/products/1'
}

4. Test Your New API

# Test locally first
PORT=3001 npm start

# Test endpoint
curl "http://localhost:3001/api/products?limit=3"

# Deploy to production
git add . && git commit -m "Add products API"
# Then redeploy using manual method

📄 Adding New HTML Pages

1. Create Route Handler

Add to routes/pages.js:

// Example: Adding a contact page
router.get('/contact', (req, res) => {
  res.render('contact', {
    title: 'Contact Us - Multi-API Server',
    contactInfo: {
      email: 'contact@yourdomain.com',
      phone: '+1 (555) 123-4567',
      address: '123 API Street, Tech City'
    }
  });
});

2. Create EJS Template

Create views/contact.ejs:

<div class="card">
    <div class="card-header">
        <h1><%= title %></h1>
    </div>
    <div class="card-body">
        <div class="grid">
            <div>
                <h3>Get in Touch</h3>
                <p><strong>Email:</strong> <%= contactInfo.email %></p>
                <p><strong>Phone:</strong> <%= contactInfo.phone %></p>
                <p><strong>Address:</strong> <%= contactInfo.address %></p>
            </div>
            <div>
                <h3>Contact Form</h3>
                <form>
                    <div style="margin-bottom: 1rem;">
                        <label>Name:</label>
                        <input type="text" style="width: 100%; padding: 0.5rem;">
                    </div>
                    <div style="margin-bottom: 1rem;">
                        <label>Email:</label>
                        <input type="email" style="width: 100%; padding: 0.5rem;">
                    </div>
                    <div style="margin-bottom: 1rem;">
                        <label>Message:</label>
                        <textarea style="width: 100%; padding: 0.5rem; height: 100px;"></textarea>
                    </div>
                    <button type="submit" class="btn">Send Message</button>
                </form>
            </div>
        </div>
    </div>
</div>

3. Update Navigation

Edit views/layout.ejs to add the new page to navigation:

<ul class="nav-links">
    <li><a href="/">Home</a></li>
    <li><a href="/about">About</a></li>
    <li><a href="/api-explorer">API Explorer</a></li>
    <li><a href="/docs">Docs</a></li>
    <li><a href="/contact">Contact</a></li>  <!-- Add this -->
    <li><a href="/status">Status</a></li>
    <li><a href="/health">Health</a></li>
</ul>

📚 Adding Markdown Documentation

1. Create Markdown File

Create new .md file in content/ directory:

Example: content/getting-started.md

# Getting Started Guide

This guide helps you get started with the Multi-API Server.

## Quick Start

### 1. Health Check

First, verify the server is running:

```bash
curl "https://api.app.lobott.com/health"

2. Explore APIs

Visit the API explorer to test endpoints interactively:
https://api.app.lobott.com/api-explorer

3. Authentication

Currently, no authentication is required for public endpoints.

Available Endpoints

Users API

  • GET /api/users - List all users
  • GET /api/users/:id - Get specific user

Posts API

  • GET /api/posts - List all posts
  • GET /api/posts/:id - Get specific post

Rate Limiting

Currently no rate limiting is implemented.

Support

For support, visit the status page: /status


### 2. Auto-generated Index

The documentation index at `/docs` automatically detects new markdown files and displays them with:
- Auto-extracted title (first # heading)
- Auto-generated description (first paragraph)
- Direct links to view the document

### 3. Multiple Format Access

Each markdown document is available in multiple formats:
- **HTML**: `/docs/getting-started` (rendered with syntax highlighting)
- **Raw**: `/docs/getting-started/raw` (plain markdown)
- **JSON**: `/docs/getting-started/json` (structured data with metadata)

## 🔄 Deployment Process

### 1. Development Testing

```bash
# Test locally
PORT=3001 npm start

# Test your changes
curl "http://localhost:3001/your-new-endpoint"

2. Commit Changes

git add .
git commit -m "Add new feature: describe what you added"

3. Deploy to Production

Use the manual deployment method (reliable for your server):

# Create deployment archive
tar -czf ../api-app-update.tar.gz --exclude='.git' --exclude='node_modules' --exclude='*.log' .

# Upload to server
scp ../api-app-update.tar.gz root@104.248.219.197:/tmp/

# Deploy with zero downtime
ssh root@104.248.219.197 '
cd /tmp && rm -rf api-deploy && mkdir api-deploy && cd api-deploy &&
tar -xzf /tmp/api-app-update.tar.gz &&
docker build -t dokku/api:new . &&
docker stop api.web.1 2>/dev/null || true &&
docker rm api.web.1 2>/dev/null || true &&
docker run -d --name api.web.1 --restart=always -p 3000 --label=dokku=api dokku/api:new &&
echo "Deployment complete!"
'

4. Verify Deployment

# Check health
curl "https://api.app.lobott.com/health"

# Test your new features
curl "https://api.app.lobott.com/your-new-endpoint"

🎨 Styling and Templates

Custom CSS

Add styles to public/css/style.css:

.your-custom-class {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 4px;
}

Template Patterns

Follow these patterns for consistency:

Page Template Structure:

<div class="card">
    <div class="card-header">
        <h1><%= title %></h1>
    </div>
    <div class="card-body">
        <!-- Your content here -->
    </div>
</div>

API Response Structure:

// Success response
{
  "success": true,
  "count": 10,
  "data": [...],
  "metadata": {...}
}

// Error response
{
  "success": false,
  "message": "Error description",
  "error_code": "SPECIFIC_ERROR"
}

🔍 Debugging and Logs

Local Development

# Run with debug output
DEBUG=* npm start

# Or with specific debug namespace
DEBUG=api:* npm start

Production Logs

# View container logs
ssh root@104.248.219.197 "docker logs api.web.1 --tail 50"

# Follow live logs
ssh root@104.248.219.197 "docker logs api.web.1 --follow"

📊 Performance Monitoring

Built-in Endpoints

  • /health - Basic health check
  • /api/stats - Server statistics
  • /status - Detailed server status

Custom Monitoring

Add monitoring to your routes:

const startTime = Date.now();
// ... your route logic ...
const responseTime = Date.now() - startTime;
console.log(`Route /api/your-endpoint took ${responseTime}ms`);

🔒 Security Best Practices

Input Validation

router.get('/api/secure-endpoint', (req, res) => {
  const { limit } = req.query;
  
  // Validate and sanitize input
  const validLimit = Math.min(Math.max(parseInt(limit) || 10, 1), 100);
  
  // Use validated input
  res.json({ limit: validLimit, data: [...] });
});

Error Handling

router.get('/api/safe-endpoint', (req, res, next) => {
  try {
    // Your logic here
    res.json({ success: true, data: result });
  } catch (error) {
    console.error('Error in safe-endpoint:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Internal server error' 
    });
  }
});

This manual covers all the common scenarios for extending your Multi-API application. The modular structure makes it easy to add new features while maintaining consistency and reliability.