/api-gen
/api-gen
Section titled “/api-gen”Purpose
Section titled “Purpose”Generate API endpoints, documentation, or client code from specifications. Accelerates API development by creating boilerplate code, OpenAPI specs, and client SDKs.
/api-gen [resource-name-or-spec]Arguments
Section titled “Arguments”- resource-name-or-spec:
- Resource name:
User,Order,Product- Generate CRUD API - OpenAPI spec path:
openapi.yaml- Generate from specification - Description:
"User management API"- Generate from description
- Resource name:
Workflow
Section titled “Workflow”Step 1: Define Resource
Section titled “Step 1: Define Resource”-
Identify resource properties
- Field names and types
- Required vs optional
- Validation rules
-
Define relationships
- One-to-many
- Many-to-many
- Foreign keys
-
Determine operations
- CRUD operations needed
- Custom endpoints
- Business logic
Step 2: Generate Code
Section titled “Step 2: Generate Code”-
Create model/schema
- Database model
- Validation schema
- Type definitions
-
Create routes/endpoints
- HTTP methods
- Path parameters
- Request/response handling
-
Add validation
- Input validation
- Type checking
- Error handling
-
Generate tests
- Endpoint tests
- Validation tests
- Error case tests
Step 3: Document
Section titled “Step 3: Document”-
Create OpenAPI spec
- Endpoint descriptions
- Request/response schemas
- Authentication
-
Add examples
- Request examples
- Response examples
- cURL commands
-
Document errors
- Error codes
- Error messages
- Resolution steps
Examples
Section titled “Examples”Generate CRUD API for Resource
Section titled “Generate CRUD API for Resource”/api-gen UserCreates:
src/models/user.ts- Data modelsrc/routes/user.ts- API routessrc/controllers/user.ts- Business logictests/user.test.ts- Test suitedocs/api/user.md- API documentation
Generate from OpenAPI Spec
Section titled “Generate from OpenAPI Spec”/api-gen openapi.yamlGenerates code matching the specification.
Generate with Description
Section titled “Generate with Description”/api-gen "Product catalog API with categories and tags"Creates API based on natural language description.
Output
Section titled “Output”## API Generated: User Management
### Endpoints Created
| Method | Path | Description ||--------|------|-------------|| GET | /api/users | List all users || POST | /api/users | Create new user || GET | /api/users/:id | Get user by ID || PUT | /api/users/:id | Update user || DELETE | /api/users/:id | Delete user || GET | /api/users/:id/posts | Get user's posts |
### Files Created
#### Model- `src/models/user.ts` ```typescript export interface User { id: string; email: string; name: string; createdAt: Date; updatedAt: Date; }
export const UserSchema = z.object({ email: z.string().email(), name: z.string().min(1).max(100), });Routes
Section titled “Routes”src/routes/user.tsrouter.get('/users', listUsers);router.post('/users', validateBody(UserSchema), createUser);router.get('/users/:id', getUser);router.put('/users/:id', validateBody(UserSchema), updateUser);router.delete('/users/:id', deleteUser);
Controller
Section titled “Controller”src/controllers/user.tsexport async function createUser(req, res) {const user = await db.user.create({data: req.body,});res.status(201).json(user);}// ... other handlers
tests/user.test.tsdescribe('User API', () => {it('should create user', async () => {const res = await request(app).post('/api/users').send({ email: 'test@example.com', name: 'Test' });expect(res.status).toBe(201);expect(res.body).toHaveProperty('id');});});
Documentation
Section titled “Documentation”docs/api/user.md- Full API documentation
OpenAPI Specification
Section titled “OpenAPI Specification”Generated openapi.yaml:
openapi: 3.0.0info: title: User API version: 1.0.0paths: /api/users: get: summary: List all users responses: '200': description: Success content: application/json: schema: type: array items: $ref: '#/components/schemas/User' post: summary: Create new user requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateUser' responses: '201': description: CreatedNext Steps
Section titled “Next Steps”- ✅ API endpoints generated
- 🔧 Add authentication middleware
- 🔧 Implement business validation
- 🔧 Add pagination to list endpoint
- 📝 Review and customize as needed
## Generation Modes
### CRUD Generation```bash/api-gen ProductFull Create, Read, Update, Delete operations
Spec-Based Generation
Section titled “Spec-Based Generation”/api-gen swagger.jsonGenerate from existing OpenAPI/Swagger spec
Client Generation
Section titled “Client Generation”/api-gen --client openapi.yamlGenerate TypeScript/Python client SDK
Documentation Only
Section titled “Documentation Only”/api-gen --docs-only api/Generate documentation for existing endpoints
| Flag | Description |
|---|---|
--framework=[express|fastapi|nestjs] | Target framework |
--db=[postgres|mongodb|prisma] | Database/ORM |
--auth | Include authentication |
--client | Generate client SDK |
--docs-only | Documentation only |
--test-framework=[jest|vitest|pytest] | Testing framework |
Advanced Examples
Section titled “Advanced Examples”Express + PostgreSQL + Auth
Section titled “Express + PostgreSQL + Auth”/api-gen Order \ --framework=express \ --db=postgres \ --authFastAPI + MongoDB
Section titled “FastAPI + MongoDB”/api-gen Product \ --framework=fastapi \ --db=mongodbGenerate Client SDK
Section titled “Generate Client SDK”/api-gen --client openapi.yamlCreates TypeScript client:
import { UserAPI } from './generated/client';
const api = new UserAPI({ baseUrl: 'http://localhost:3000' });const users = await api.getUsers();const user = await api.createUser({ email: 'test@example.com', name: 'Test User'});Resource Definition
Section titled “Resource Definition”When generating from resource name, you’ll be asked:
### Define Resource: User
**Fields:**1. email (string, required, unique)2. name (string, required)3. role (enum: user|admin, optional, default: user)4. createdAt (datetime, auto)
**Relationships:**- Has many: Post- Belongs to: Organization (optional)
**Custom Endpoints:**- POST /users/:id/verify-email- POST /users/:id/reset-password
**Validation:**- Email must be valid format- Name: 1-100 characters- Password: min 8 characters
Proceed with generation? (y/n)OpenAPI Templates
Section titled “OpenAPI Templates”Complete Endpoint
Section titled “Complete Endpoint”/api/orders: post: summary: Create new order tags: - Orders security: - bearerAuth: [] requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateOrder' examples: basic: value: items: - productId: "123" quantity: 2 shippingAddress: street: "123 Main St" city: "New York" responses: '201': description: Order created content: application/json: schema: $ref: '#/components/schemas/Order' '400': description: Invalid input '401': description: UnauthorizedBest Practices
Section titled “Best Practices”- Start with Design: Define API before generating
- Review Generated Code: Don’t blindly accept all generated code
- Customize: Generated code is a starting point
- Add Business Logic: Implement domain-specific validation
- Security: Add authentication and authorization
- Testing: Extend generated tests with edge cases
Use Cases
Section titled “Use Cases”Rapid Prototyping
Section titled “Rapid Prototyping”# Quickly scaffold multiple resources/api-gen User/api-gen Post/api-gen CommentAPI-First Development
Section titled “API-First Development”# Design spec, then generate# 1. Create openapi.yaml# 2. Generate code/api-gen openapi.yamlClient SDK Distribution
Section titled “Client SDK Distribution”# Generate client for API consumers/api-gen --client openapi.yamlDocumentation Generation
Section titled “Documentation Generation”# Document existing API/api-gen --docs-only src/api/