@cwt-build/api-mocker
v0.1.0
Published
Lightweight API mocking tool with realistic data generation for frontend development
Maintainers
Readme
@cwt-build/api-mocker
Lightweight API mocking tool with realistic data generation for frontend development
Built by Create With Tech (CWT) - Empowering developers with practical tools.
🎯 Features
- Smart Data Generation: Auto-generates realistic mock data based on field types
- Stateful by Default: POST creates, GET retrieves, PUT updates, DELETE removes - maintains state across requests
- Zero Config for Common Patterns: Pagination, filtering, and sorting work out of the box
- TypeScript First: Full type safety and IntelliSense support
- Minimal Setup: Get started with just a schema definition
- Realistic Delays: Simulate network latency for more realistic development
📦 Installation
npm install @cwt-build/api-mockeror
yarn add @cwt-build/api-mocker🚀 Quick Start
import { createMockAPI } from '@cwt-build/api-mocker';
// Define your API structure
const api = createMockAPI({
'/users': {
schema: {
id: 'uuid',
name: 'fullName',
email: 'email',
age: 'number',
city: 'city',
},
count: 50, // Generate 50 users
},
});
// Use it like a real API
const response = await api.get('/users', { page: 1, limit: 10 });
console.log(response.data);📖 Usage Examples
Basic CRUD Operations
// GET all resources (with pagination)
const users = await api.get('/users', {
page: 1,
limit: 10,
});
// GET single resource by ID
const user = await api.getById('/users', 'user-id-123');
// POST - Create new resource
const newUser = await api.post('/users', {
name: 'John Doe',
email: '[email protected]',
});
// PUT - Update resource
const updated = await api.put('/users', 'user-id-123', {
name: 'Jane Doe',
});
// DELETE - Remove resource
const deleted = await api.delete('/users', 'user-id-123');Pagination & Sorting
// Paginated results
const response = await api.get('/products', {
page: 2,
limit: 20,
});
// Sorted results
const sorted = await api.get('/products', {
sort: 'price',
order: 'asc', // or 'desc'
});
// Response includes metadata
console.log(response.data);
// {
// data: [...],
// meta: {
// page: 1,
// limit: 10,
// total: 50,
// totalPages: 5
// }
// }Multiple Endpoints
const api = createMockAPI({
'/users': {
schema: { id: 'uuid', name: 'fullName', email: 'email' },
count: 100,
},
'/products': {
schema: {
id: 'uuid',
name: 'string',
price: 'price',
description: 'description',
},
count: 50,
},
'/orders': {
schema: {
id: 'uuid',
userId: 'uuid',
productId: 'uuid',
date: 'date',
},
count: 200,
},
});Custom Seed Data
const api = createMockAPI({
'/categories': {
schema: { id: 'uuid', name: 'string' },
seed: [
{ id: '1', name: 'Electronics' },
{ id: '2', name: 'Clothing' },
{ id: '3', name: 'Food' },
],
},
});Network Delay Simulation
const api = createMockAPI(
{
'/users': {
schema: { id: 'uuid', name: 'fullName' },
count: 50,
},
},
{
baseDelay: 500, // 500ms delay
randomDelay: true, // Randomize delay (0-500ms)
},
);🔧 Available Data Types
| Type | Example Output | Description |
| ------------- | --------------------- | ----------------------- |
| uuid | "a1b2c3d4-..." | UUID v4 |
| string | "lorem" | Random word |
| number | 742 | Random integer (1-1000) |
| boolean | true | Random boolean |
| email | "[email protected]" | Realistic email |
| fullName | "John Doe" | Full name |
| firstName | "John" | First name |
| lastName | "Doe" | Last name |
| date | "2024-01-15T..." | ISO date string |
| url | "https://..." | URL |
| phone | "555-1234" | Phone number |
| address | "123 Main St" | Street address |
| city | "New York" | City name |
| country | "United States" | Country name |
| company | "Tech Corp" | Company name |
| jobTitle | "Software Engineer" | Job title |
| description | "Lorem ipsum..." | Paragraph of text |
| price | 29.99 | Price (number) |
| image | "https://..." | Image URL |
🛠️ API Reference
createMockAPI(config, options?)
Creates a new mock API instance.
Parameters:
config: Object defining endpoints and their schemasoptions(optional):baseDelay: Base delay in milliseconds (default: 0)randomDelay: Randomize delay (default: false)
Returns: MockAPI instance
MockAPI Methods
get(endpoint, params?)
Get all resources from an endpoint.
Parameters:
endpoint: The API endpoint (e.g.,/users)params(optional):page: Page number (for pagination)limit: Items per pagesort: Field to sort byorder:'asc'or'desc'- Any other key for filtering
Returns: Promise<MockResponse>
getById(endpoint, id)
Get a single resource by ID.
Returns: Promise<MockResponse>
post(endpoint, body)
Create a new resource.
Returns: Promise<MockResponse>
put(endpoint, id, body)
Update an existing resource.
Returns: Promise<MockResponse>
delete(endpoint, id)
Delete a resource.
Returns: Promise<MockResponse>
reset(endpoint?)
Reset data for an endpoint (or all endpoints if no argument).
getAllData(endpoint)
Get raw data array for inspection/debugging.
💡 Use Cases
- Frontend Development: Build UI components before backend is ready
- Demos & Presentations: Quickly create realistic demo data
- Testing: Generate consistent test data for integration tests
- Prototyping: Rapidly prototype applications with working data
- Tutorials: Create educational content with working examples
🎓 Learn More
This package is part of the CWT ecosystem. Check out more resources:
- Website: cwt.build
- Tutorials: Find step-by-step guides on our platform
- Support: Open an issue on GitHub
📄 License
MIT © Create With Tech (CWT)
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
🐛 Found a Bug?
If you find a bug or have a feature request, please open an issue on our GitHub repository.
Made with ❤️ by CWT - Teaching, Building, Innovating
