blog-api-v2-example
v2.0.1
Published
Blog API using API Forge V2 configuration system
Downloads
6
Readme
Blog API V2 - Configuration Driven Example
This example demonstrates a complete blog API using API Forge V2's configuration-driven approach.
Features
- 🔐 Authentication: JWT-based auth with sessions
- 📝 Blog Posts: Full CRUD operations with pagination
- 💬 Comments: Nested comments on posts
- 👤 User Management: Profile updates and roles
- 📁 File Upload: Image uploads with processing
- 🚀 Real-time Updates: SSE for live notifications
- 📚 API Documentation: Auto-generated Swagger docs
- 🔧 TypeScript SDK: Auto-generated client library
- 🛡️ Security: Rate limiting, input validation, CSRF protection
- ⚡ Caching: Redis-based response caching
Quick Start
1. Install Dependencies
cd examples/blog-api-v2
bun install2. Setup Environment
Copy the example environment file:
cp .env.example .envEdit .env with your configuration:
# Required
JWT_SECRET=your-secret-key-change-in-production
# Optional (defaults provided)
PORT=3001
REDIS_URL=redis://localhost:63793. Start the Server
bun run server.tsThe server will start at http://localhost:3001
4. Access Resources
- API Documentation: http://localhost:3001/docs
- Health Check: http://localhost:3001/health
- API Info: http://localhost:3001/api
Project Structure
blog-api-v2/
├── .api-forge.json # Main configuration file
├── .env.example # Environment variables template
├── server.ts # Minimal server code (< 100 lines!)
├── api-configs/ # API endpoint configurations
│ ├── auth.json # Authentication endpoints
│ ├── posts.json # Blog post endpoints
│ ├── comments.json # Comment endpoints
│ ├── users.json # User management
│ └── events.json # SSE real-time events
├── handlers/ # Custom business logic
│ ├── auth.js # Auth handlers
│ ├── posts.js # Post handlers
│ ├── comments.js # Comment handlers
│ ├── users.js # User handlers
│ └── events.js # SSE handlers
└── sdk/ # Auto-generated TypeScript SDKConfiguration Highlights
Plugin Configuration
All plugins are configured in .api-forge.json:
{
"plugins": {
"@api-forge/redis": {
"enabled": "${REDIS_ENABLED:-true}",
"config": {
"url": "${REDIS_URL:-redis://localhost:6379}"
}
},
"@api-forge/auth": {
"enabled": true,
"config": {
"jwt": {
"secret": "${JWT_SECRET}"
}
}
}
}
}API Configuration
Each API endpoint is defined in a JSON file:
{
"id": "posts",
"route": {
"path": "/api/posts/:id?",
"methods": ["GET", "POST", "PUT", "DELETE"]
},
"auth": {
"required": true,
"roles": {
"DELETE": ["admin"]
}
},
"cache": {
"enabled": true,
"ttl": 300
}
}API Endpoints
Authentication
# Register
curl -X POST http://localhost:3001/api/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"password123","name":"John Doe"}'
# Login
curl -X POST http://localhost:3001/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"password123"}'Posts
# List posts
curl http://localhost:3001/api/posts
# Get single post
curl http://localhost:3001/api/posts/1
# Create post (requires auth)
curl -X POST http://localhost:3001/api/posts \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"title":"My Post","content":"Hello World","status":"published"}'Real-time Events (SSE)
// Connect to SSE endpoint
const eventSource = new EventSource(
'http://localhost:3001/api/events',
{ headers: { 'Authorization': 'Bearer YOUR_TOKEN' } }
);
eventSource.addEventListener('post:created', (event) => {
const data = JSON.parse(event.data);
console.log('New post created:', data);
});TypeScript SDK
The SDK is auto-generated when the server starts:
import { BlogAPI } from './sdk';
const api = new BlogAPI({
baseUrl: 'http://localhost:3001',
token: 'YOUR_JWT_TOKEN'
});
// Type-safe API calls
const posts = await api.posts.list({ page: 1, limit: 10 });
const post = await api.posts.create({
title: 'My Post',
content: 'Hello World'
});Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| NODE_ENV | Environment (development/production) | development |
| PORT | Server port | 3001 |
| REDIS_ENABLED | Enable Redis caching | true |
| REDIS_URL | Redis connection URL | redis://localhost:6379 |
| JWT_SECRET | Secret for JWT signing | (required) |
| CORS_ORIGIN | Allowed CORS origins | * |
| STORAGE_TYPE | File storage type (local/s3) | local |
Key Differences from V1
- No Plugin Code: All plugins configured in JSON
- Environment Variables: Full support with defaults
- Minimal Server Code: < 100 lines vs 500+ in V1
- Centralized Config: Single
.api-forge.jsonfile - Better Deployment: Environment-specific configs
Production Deployment
- Set production environment variables
- Use production configuration:
NODE_ENV=production bun run server.ts - Configure reverse proxy (nginx/caddy)
- Set up process manager (PM2/systemd)
Extending the API
Add New Endpoint
- Create configuration in
api-configs/ - Add handlers in
handlers/if needed - Restart server (or use hot reload in dev)
Add New Plugin
- Install the plugin package
- Add configuration to
.api-forge.json - Set any required environment variables
Troubleshooting
Redis Connection Failed
- Ensure Redis is running:
redis-cli ping - Check
REDIS_URLenvironment variable
Authentication Errors
- Verify
JWT_SECRETis set - Check token expiration
SDK Generation Failed
- Ensure write permissions for
./sdkdirectory - Check console for specific errors
