Back to Dashboard

Add New API Guide

Step-by-step guide to add new mock APIs to the Tarekat Mock Server

Plan Your API

Before adding a new API, define its purpose and structure:

Planning Checklist:

Create Mock Data

Create a JSON file in the mocks/ directory with your mock responses:

// mocks/your-service.json
{
  "success": {
    "code": "S00200",
    "message": "Success",
    "data": {
      "id": "12345",
      "name": "Sample Item",
      "status": "active",
      "createdAt": "2024-01-01T00:00:00Z"
    }
  },
  "list": [
    {
      "id": "1",
      "name": "Item 1",
      "status": "active"
    },
    {
      "id": "2", 
      "name": "Item 2",
      "status": "inactive"
    }
  ]
}
// mocks/complex-service.json
{
  "responses": {
    "create": {
      "success": {
        "code": "S00200",
        "message": "Created successfully",
        "data": {
          "referenceNumber": "REF{{timestamp}}",
          "status": "pending",
          "details": {
            "submittedBy": "user123",
            "submissionDate": "{{currentDate}}",
            "estimatedCompletion": "{{futureDate}}"
          }
        }
      }
    },
    "update": {
      "success": {
        "code": "S00200", 
        "message": "Updated successfully",
        "data": {
          "referenceNumber": "{{refNumber}}",
          "status": "updated",
          "lastModified": "{{currentDate}}"
        }
      }
    }
  }
}
// Error scenarios in your mock data
{
  "errors": {
    "validation": {
      "code": "E00400",
      "message": "Validation failed",
      "details": {
        "field": "{{invalidField}}",
        "reason": "Required field missing"
      }
    },
    "notFound": {
      "code": "E00404", 
      "message": "Resource not found",
      "details": {
        "requestedId": "{{requestedId}}",
        "suggestion": "Please check the ID and try again"
      }
    },
    "serverError": {
      "code": "E00500",
      "message": "Internal server error",
      "details": {
        "timestamp": "{{currentDate}}",
        "errorId": "ERR{{timestamp}}"
      }
    }
  }
}
Tip: Use placeholders like {{timestamp}}, {{currentDate}} for dynamic data in your middleware.

Create Middleware

Create a middleware file in the middlewares/ directory to handle your API logic:

// middlewares/your-service.js
module.exports = function(mocks) {
  return function(req, res, next) {
    const path = req.path;
    const method = req.method;

    // Handle your specific endpoints
    if (path.startsWith('/v1/your-service/')) {
      
      // GET /v1/your-service/list
      if (path === '/v1/your-service/list' && method === 'GET') {
        return res.json(mocks.yourService.list);
      }

      // POST /v1/your-service/create
      if (path === '/v1/your-service/create' && method === 'POST') {
        const response = { ...mocks.yourService.success };
        
        // Add dynamic data
        response.data.id = generateId();
        response.data.createdAt = new Date().toISOString();
        
        return res.json(response);
      }

      // GET /v1/your-service/:id
      const idMatch = path.match(/^\/v1\/your-service\/(\d+)$/);
      if (idMatch && method === 'GET') {
        const id = idMatch[1];
        const response = { ...mocks.yourService.success };
        response.data.id = id;
        
        return res.json(response);
      }

      // Handle errors
      if (path === '/v1/your-service/error-test') {
        return res.status(400).json(mocks.yourService.errors.validation);
      }
    }

    // Continue to next middleware
    next();
  };
};

// Helper functions
function generateId() {
  return Math.floor(Math.random() * 1000000).toString();
}

function getCurrentDate() {
  return new Date().toISOString();
}
Best Practice: Always call next() if your middleware doesn't handle the request.

Register Middleware

Add your middleware to the main server configuration:

// server.js - Add these lines

// Import your middleware
const yourServiceMiddleware = require('./middlewares/your-service');

// Load your mock data
const yourServiceMocks = require('./mocks/your-service.json');

// Add mocks to the main mocks object
const mocks = {
  // ... existing mocks
  yourService: yourServiceMocks
};

// Register middleware (ORDER MATTERS!)
server.use(yourServiceMiddleware(mocks));

// Make sure this comes BEFORE the json-server router
server.use('/api', router);
Important: Add your middleware BEFORE the server.use('/api', router) line to ensure it gets processed first.
File Structure After Changes: ├── middlewares/ │ ├── auth.js │ ├── infath.js │ └── your-service.js ← New file ├── mocks/ │ ├── access-tokens.json │ ├── infath.json │ └── your-service.json ← New file └── server.js ← Updated

Test Your API

Test your new API endpoints to ensure they work correctly:

# Test GET endpoint
curl -X GET http://localhost:3000/v1/your-service/list

# Test POST endpoint  
curl -X POST http://localhost:3000/v1/your-service/create \
  -H "Content-Type: application/json" \
  -d '{"name": "Test Item", "description": "Test description"}'

# Test GET with ID
curl -X GET http://localhost:3000/v1/your-service/123

# Test error scenario
curl -X GET http://localhost:3000/v1/your-service/error-test
#!/bin/bash
# test-your-service.sh

echo "Testing Your Service API..."

BASE_URL="http://localhost:3000"

echo "1. Testing list endpoint..."
curl -s "$BASE_URL/v1/your-service/list" | jq '.'

echo -e "\n2. Testing create endpoint..."
curl -s -X POST "$BASE_URL/v1/your-service/create" \
  -H "Content-Type: application/json" \
  -d '{"name": "Test Item"}' | jq '.'

echo -e "\n3. Testing get by ID..."
curl -s "$BASE_URL/v1/your-service/123" | jq '.'

echo -e "\n4. Testing error scenario..."
curl -s "$BASE_URL/v1/your-service/error-test" | jq '.'

echo -e "\nTesting complete!"
// Postman Collection JSON
{
  "info": {
    "name": "Your Service API Tests",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "Get List",
      "request": {
        "method": "GET",
        "header": [],
        "url": {
          "raw": "{{baseUrl}}/v1/your-service/list",
          "host": ["{{baseUrl}}"],
          "path": ["v1", "your-service", "list"]
        }
      }
    },
    {
      "name": "Create Item", 
      "request": {
        "method": "POST",
        "header": [
          {
            "key": "Content-Type",
            "value": "application/json"
          }
        ],
        "body": {
          "mode": "raw",
          "raw": "{\n  \"name\": \"Test Item\",\n  \"description\": \"Test description\"\n}"
        },
        "url": {
          "raw": "{{baseUrl}}/v1/your-service/create",
          "host": ["{{baseUrl}}"],
          "path": ["v1", "your-service", "create"]
        }
      }
    }
  ],
  "variable": [
    {
      "key": "baseUrl",
      "value": "http://localhost:3000"
    }
  ]
}

Restart and Deploy

Restart the server to load your new API:

# Stop the current server
docker-compose down

# Rebuild and start with your changes
docker-compose up --build -d

# Check server logs
docker-compose logs -f

# Test that server is running
curl http://localhost:3000/health
Success! Your new API should now be available at http://localhost:3000/v1/your-service/*

Quick Reference

  • Middleware Order: Your middleware → Other middlewares → JSON-server router
  • Mock Data Location: ./mocks/your-service.json
  • Middleware Location: ./middlewares/your-service.js
  • Server Config: ./server.js
  • Test Your API: curl http://localhost:3000/v1/your-service/endpoint
  • Restart Server: docker-compose down && docker-compose up --build -d
  • View Logs: docker-compose logs -f
  • Health Check: curl http://localhost:3000/health

Documentation & Examples

Study existing implementations for reference:

Reference Examples:

Pro Tip: Keep your API consistent with existing patterns. Use similar response structures and error handling for better developer experience.

Congratulations!

You've successfully learned how to add new APIs to the Tarekat Mock Server. Your new endpoints are now ready for frontend development and testing!

Return to Dashboard