/add-api-route
Create new API endpoints in your Cloudflare Workers application.
Overview
The /add-api-route command creates RESTful API endpoints using the Hono framework, optimized for Cloudflare Workers edge runtime.
Usage
bash
/add-api-route "Route description"Examples
bash
# User management endpoint
/add-api-route "GET /api/users - List all users with pagination"
# Data processing endpoint
/add-api-route "POST /api/process - Process uploaded CSV files"
# WebSocket endpoint
/add-api-route "WebSocket /api/ws/chat - Real-time chat connection"What Gets Created
- Route Handler -
src/routes/[endpoint].ts - Middleware - Authentication, validation, rate limiting
- Type Definitions - Request/response types
- Tests - Unit tests for the endpoint
- Documentation - OpenAPI spec updates
Example Implementation
typescript
// src/routes/users.ts
import { Hono } from 'hono';
import { z } from 'zod';
import { zValidator } from '@hono/zod-validator';
const app = new Hono();
const querySchema = z.object({
page: z.string().optional().default('1'),
limit: z.string().optional().default('10'),
});
app.get('/api/users',
zValidator('query', querySchema),
async (c) => {
const { page, limit } = c.req.valid('query');
// Fetch from D1 database
const users = await c.env.DB.prepare(
'SELECT * FROM users LIMIT ? OFFSET ?'
).bind(limit, (page - 1) * limit).all();
return c.json({
users: users.results,
pagination: {
page: parseInt(page),
limit: parseInt(limit),
total: users.meta.total
}
});
}
);
export default app;Best Practices
- Use proper HTTP methods (GET, POST, PUT, DELETE)
- Implement request validation with Zod
- Add authentication middleware where needed
- Return consistent error responses
- Use KV for caching when appropriate
