api-endpoint-scaffolder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Endpoint Scaffolder

API端点脚手架

Instructions

操作指南

When creating a new API endpoint:
  1. Identify the framework (Express, Next.js, FastAPI, etc.)
  2. Determine HTTP method (GET, POST, PUT, PATCH, DELETE)
  3. Define request/response types
  4. Implement with best practices
创建新API端点时:
  1. 识别框架(Express、Next.js、FastAPI等)
  2. 确定HTTP方法(GET、POST、PUT、PATCH、DELETE)
  3. 定义请求/响应类型
  4. 遵循最佳实践实现

Templates

模板

Next.js App Router (TypeScript)

Next.js App Router(TypeScript)

typescript
// app/api/[resource]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

const RequestSchema = z.object({
  // Define your schema
});

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    // Implementation
    return NextResponse.json({ data }, { status: 200 });
  } catch (error) {
    console.error('[API] Error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validated = RequestSchema.parse(body);
    // Implementation
    return NextResponse.json({ data }, { status: 201 });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: 'Validation failed', details: error.errors },
        { status: 400 }
      );
    }
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
typescript
// app/api/[resource]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

const RequestSchema = z.object({
  // Define your schema
});

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    // Implementation
    return NextResponse.json({ data }, { status: 200 });
  } catch (error) {
    console.error('[API] Error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validated = RequestSchema.parse(body);
    // Implementation
    return NextResponse.json({ data }, { status: 201 });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: 'Validation failed', details: error.errors },
        { status: 400 }
      );
    }
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

Express (TypeScript)

Express(TypeScript)

typescript
import { Router, Request, Response, NextFunction } from 'express';
import { z } from 'zod';

const router = Router();

const CreateSchema = z.object({
  // Define schema
});

router.post('/', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const data = CreateSchema.parse(req.body);
    // Implementation
    res.status(201).json({ success: true, data });
  } catch (error) {
    next(error);
  }
});

export default router;
typescript
import { Router, Request, Response, NextFunction } from 'express';
import { z } from 'zod';

const router = Router();

const CreateSchema = z.object({
  // Define schema
});

router.post('/', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const data = CreateSchema.parse(req.body);
    // Implementation
    res.status(201).json({ success: true, data });
  } catch (error) {
    next(error);
  }
});

export default router;

Best Practices

最佳实践

  1. Always validate input using Zod, Yup, or similar
  2. Use proper HTTP status codes:
    • 200: Success
    • 201: Created
    • 400: Bad Request
    • 401: Unauthorized
    • 403: Forbidden
    • 404: Not Found
    • 500: Server Error
  3. Log errors but don't expose internals to clients
  4. Use consistent response format
  5. Add rate limiting for public endpoints
  6. Document with OpenAPI/Swagger when possible
  1. 始终使用Zod、Yup或类似工具验证输入
  2. 使用正确的HTTP状态码:
    • 200: 请求成功
    • 201: 创建成功
    • 400: 请求参数错误
    • 401: 未授权
    • 403: 禁止访问
    • 404: 资源未找到
    • 500: 服务器内部错误
  3. 记录错误但不要向客户端暴露内部细节
  4. 使用统一的响应格式
  5. 为公开端点添加速率限制
  6. 尽可能使用OpenAPI/Swagger进行文档编写