- Overview
- Quick Start
- Creating API Endpoints
- Data Management
- Serving Static Resources
- Advanced Features
- Request Logging
- Configuration
- MCP Server Integration (Experimental)
- Development Workflow
- Contributing
- Resources
A quick-to-setup standalone local mock API framework for developing API endpoints on localhost. Perfect for testing API code, rapid prototyping, and developing frontend clients before deploying to live servers.
Built with MSW and TypeScript, this framework can run directly on your local machine or in Docker containers.
- Static File Serving: JSON, text, images (with dynamic resizing), videos, and markdown
- Database Operations: CRUD operations with persistent or temporary mock data
- AWS Lambda Testing: Develop and test Lambda functions locally
- Custom Middleware: Transform input/output with custom logic
- Error Mocking: Test frontend error handling with configurable error responses
- Request Logging: Store and view API requests at
localhost:8000/logs
- MCP Server: Experimental LLM agent integration for server management
- Node.js 20+
- Docker
-
Clone and install dependencies
npm install
-
Start with Docker (recommended)
npm start
-
View your APIs
- Dashboard: http://localhost:8000/
- API list: http://localhost:8000/api
For active development:
npm run dev
Command | Description |
---|---|
npm start |
Start in Docker |
npm stop |
Stop and remove containers |
npm run rebuild |
Rebuild containers |
npm run nuke |
Destroy everything and rebuild |
npm run dev |
Run locally (for development) |
The system uses NextJS-style file-based routing. Create a folder in /api
that maps to your desired route.
Example: Creating /api/users
mkdir src/api/users
Create api.ts
in your new folder:
// src/api/users/api.ts
import { http, HttpResponse } from 'msw';
function handler(pathName: string) {
return [
http.get(`/${pathName}`, ({ request }) => {
// Your GET logic here
return HttpResponse.json({ users: [] });
}),
http.post(`/${pathName}`, ({ request }) => {
// Your POST logic here
return HttpResponse.json({ success: true });
}),
];
}
export default handler;
Models go in /models
directory:
// models/users.ts
import { primaryKey } from '@mswjs/data';
export const userModel = {
id: primaryKey(String),
name: String,
email: String,
};
Add to db.ts
:
import { userModel } from './models/users';
export const db = factory({
user: userModel,
// ... other models
});
Using db.user.toHandlers('rest')
automatically creates:
GET /users
- List all usersGET /users/:id
- Get user by IDPOST /users
- Create userPUT /users/:id
- Update userDELETE /users/:id
- Delete user
Choose one of three approaches:
Add data via POST/PUT requests (temporary, lost on restart)
Use seeders with faker.js for random data:
// seeders/user-seeder.ts
import { faker } from '@faker-js/faker';
import { db } from '../db';
export function seedUsers() {
for (let i = 0; i < 10; i++) {
db.user.create({
id: faker.string.uuid(),
name: faker.person.fullName(),
email: faker.internet.email(),
});
}
}
Create data.json
in /data
folder for consistent data across restarts.
For large database files, images, or videos:
# Track database files
git lfs track --filename src/data/data.json
# Track image files
git lfs track "*.png"
Store files in src/resources/{images|videos}
and access via:
http://localhost:8000/api/images/placeholder.png
http://localhost:8000/api/videos/sample.mp4
List all available media by visiting the media root folder (/api/{images|videos}) in a browser or by sending a GET request to
/api/{images|videos}/list
This path returns a JSON object describing the media type and available files in the /resources/{images|videos} folder.
{
"mediaType": "image",
"files": [
"placeholder.png",
"placeholder2.png"
]
}
Resize PNG images by adding width and height parameters:
http://localhost:8000/api/images/placeholder.png?width=300&height=500
Store in src/resources/markdown
with code highlighting support:
http://localhost:8000/api/markdown/demo
Store in src/resources/json
:
http://localhost:8000/api/json/demo
Extract URL parameters and add custom logic:
// URL parameters: /api/bikes/?type=KawasakiNinja
const type = url.searchParams.get('type');
// Dynamic paths: /api/images/:imageId
const imageId = url.pathname.split('/').pop();
Mock API errors for frontend testing:
# Default 404 error
http://localhost:8000/api/error
# Custom error
http://localhost:8000/api/error?status=500&message=Internal%20Server%20Error
Set CORS headers in your handlers:
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*', // or 'localhost:3000'
}
Develop Lambda functions in src/lambdas
directory. Use requestToApiGatewayProxyEvent
utility to convert MSW requests to AWS API Gateway format.
Monitor API requests and responses at localhost:8000/logs
.
Set environment variables in .env
:
LOG_REQUESTS=ON
DELETE_LOGS_ON_SERVER_RESTART=ON
Add to your handlers:
import logger from '../../utilities/logger';
logger({
data: extractedData,
pathName,
type: 'GET',
});
Customize your setup in .env
:
# Change API prefix (default: "api")
USE_API_URL_PREFIX=api
# Change port (default: 8000)
SERVER_PORT=8000
# Logging
LOG_REQUESTS=ON
DELETE_LOGS_ON_SERVER_RESTART=ON
With different USE_API_URL_PREFIX
settings:
- Default:
localhost:8000/api/users
- Empty:
localhost:8000/users
- Custom:
localhost:8000/things/users
-
Build MCP server
npm run mcp:build
-
Configure your LLM agent with the server path:
<path_to_project>/src/mcp/server.js
- Server Management: Start, stop, rebuild, and check endpoints
- Endpoint Creation: Generate new API endpoints via LLM
- Media Creation: Ask the LLM to Generate images and videos to serve locally
Test the MCP server with the inspector:
npm run mcp:debug
With NVM/FNM on Windows, you may need to:
- Specify full path to node binary, or
- Add fnm aliases directory to system PATH
If changing from port 8000, update mcp/server.ts
PORT variable and rebuild:
npm run mcp:build
- Development: Use
npm run dev
for active development - Testing: Use
npm start
for Docker-based testing - File Organization: Follow the established folder structure
- Error Handling: Test error scenarios using the error endpoint
- Logging: Enable logging during development for debugging
src/
├── api/ # API endpoints (file-based routing)
├── models/ # Database models
├── seeders/ # Database seeders
├── lambdas/ # AWS Lambda functions
├── resources/ # Static files
│ ├── images/
│ ├── videos/
│ ├── markdown/
│ └── json/
├── logs/ # Request logs
├── mcp/ # MCP server files
└── utilities/ # Helper functions
This project uses MIT license. For issues with the experimental MCP server, please report them at: https://github.com/piyook/mock-api-framework-template/issues