SuperAPI AI Directory

backend/api-development

Coding & development

View repository

Updated 11-14 16:54

About this skill

Backend API Development Methodology

API Contract Management

Contract Sources

Before implementing an API,you mustread architecture.md §5 (API Design) to obtain:

  • API specification (RESTful/GraphQL)
  • Endpoint list (methods, paths, descriptions, authentication requirements)
  • Request/response format conventions
  • Error code specification

Contract Compliance Principles

  1. Strict implementation: The methods, paths, and parameters of API endpoints must be consistent with architecture.md §5
  2. Response format: Follow the unified success/error response structure
  3. Deviation record: If deviation from the contract is required, the reason must be noted in the output report
  4. Type export: Export request/response types to a shared file for frontend reference

RESTful API Design

Resource Naming Conventions

Operation HTTP Method Path Description
List GET /api/users Get user list
Details GET /api/users/:id Get a single user
Create POST /api/users Create a new user
Update PUT/PATCH /api/users/:id Update user
Delete DELETE /api/users/:id Delete user

Unified Response Format

Success Response:

{
  "success": true,
  "data": { ... },
  "message": "Operation successful"
}

Error Response:

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [{ "field": "email", "message": "Invalid email format" }]
  }
}

Pagination Conventions

Request Parameters:

GET /api/users?page=1&pageSize=20&sortBy=createdAt&order=desc

Response Format:

{
  "success": true,
  "data": {
    "items": [...],
    "pagination": {
      "page": 1,
      "pageSize": 20,
      "total": 100,
      "totalPages": 5
    }
  }
}

Request Validation

Input Validation Layers

  1. Route layer: Validate path parameters and query parameters
  2. Middleware layer: Validate request body format and required fields
  3. Service layer: Validate business rules

Validation Example

// 使用验证库(如 Zod、Joi、class-validator)
import { z } from 'zod';

const CreateUserSchema = z.object({
  name: z.string().min(1).max(100),
  email: z.string().email(),
  age: z.number().int().min(0).max(150).optional(),
});

// 在路由处理器中验证
app.post('/api/users', async (req, res) => {
  try {
    const validatedData = CreateUserSchema.parse(req.body);
    const user = await userService.create(validatedData);
    res.json({ success: true, data: user });
  } catch (error) {
    if (error instanceof z.ZodError) {
      res.status(400).json({
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Invalid input data',
          details: error.errors,
        },
      });
    }
  }
});

Common Validation Rules

  • Required fields: Ensure key fields are present
  • Type checking: String, number, boolean, date
  • Format validation: Email, URL, phone number, UUID
  • Range limits: Min/max length, numeric range
  • Business rules: Uniqueness, foreign key existence

Error Handling

Error Classification

Error Type HTTP Status Code Error Code Description
Validation error 400 VALIDATION_ERROR Input data is invalid
Authentication error 401 UNAUTHORIZED Not logged in or Token is invalid
Permission error 403 FORBIDDEN No permission to access the resource
Resource not found 404 NOT_FOUND The requested resource does not exist
Conflict error 409 CONFLICT Resource conflict (e.g., duplicate creation)
Server error 500 INTERNAL_ERROR Internal server error

Unified Error Handling Middleware

// errorHandler.ts
export function errorHandler(err: Error, req: Request, res: Response, next: NextFunction) {
  console.error(err);

  if (err instanceof ValidationError) {
    return res.status(400).json({
      success: false,
      error: {
        code: 'VALIDATION_ERROR',
        message: err.message,
        details: err.details,
      },
    });
  }

  if (err instanceof NotFoundError) {
    return res.status(404).json({
      success: false,
      error: {
        code: 'NOT_FOUND',
        message: err.message,
      },
    });
  }

  // 默认 500 错误
  res.status(500).json({
    success: false,
    error: {
      code: 'INTERNAL_ERROR',
      message: 'An unexpected error occurred',
    },
  });
}

Security Implementation

Authentication

JWT Token Example:

import jwt from 'jsonwebtoken';

// 生成 Token
export function generateToken(userId: string): string {
  return jwt.sign({ userId }, process.env.JWT_SECRET!, {
    expiresIn: '7d',
  });
}

// 验证 Token 中间件
export function authMiddleware(req: Request, res: Response, next: NextFunction) {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    return res.status(401).json({
      success: false,
      error: { code: 'UNAUTHORIZED', message: 'No token provided' },
    });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({
      success: false,
      error: { code: 'UNAUTHORIZED', message: 'Invalid token' },
    });
  }
}

Authorization

Role-Based Access Control (RBAC):

export function requireRole(...roles: string[]) {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.user || !roles.includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Insufficient permissions' },
      });
    }
    next();
  };
}

// 使用
app.delete('/api/users/:id', authMiddleware, requireRole('admin'), deleteUser);

Input Sanitization

  • SQL Injection Protection: Use parameterized queries or ORM
  • XSS Protection: Escape user input, use Content Security Policy
  • CSRF Protection: Use CSRF Token
  • File Upload: Validate file type and size

Rate Limiting

import rateLimit from 'express-rate-limit';

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 分钟
  max: 100, // 最多 100 个请求
  message: 'Too many requests, please try again later',
});

app.use('/api/', limiter);

Layered Architecture

Controller Layer

Responsibility: Handle HTTP requests and responses

// controllers/userController.ts
export class UserController {
  async getUser(req: Request, res: Response) {
    try {
      const user = await userService.getById(req.params.id);
      res.json({ success: true, data: user });
    } catch (error) {
      next(error);
    }
  }

  async createUser(req: Request, res: Response) {
    const validatedData = CreateUserSchema.parse(req.body);
    const user = await userService.create(validatedData);
    res.status(201).json({ success: true, data: user });
  }
}

Service Layer

Responsibility: Business logic encapsulation

// services/userService.ts
export class UserService {
  async getById(id: string): Promise<User> {
    const user = await userRepository.findById(id);
    if (!user) {
      throw new NotFoundError('User not found');
    }
    return user;
  }

  async create(data: CreateUserDto): Promise<User> {
    // 检查邮箱唯一性
    const existing = await userRepository.findByEmail(data.email);
    if (existing) {
      throw new ConflictError('Email already exists');
    }

    // 创建用户
    return userRepository.create(data);
  }
}

Repository Layer

Responsibility: Database operations

// repositories/userRepository.ts
export class UserRepository {
  async findById(id: string): Promise<User | null> {
    return db.user.findUnique({ where: { id } });
  }

  async findByEmail(email: string): Promise<User | null> {
    return db.user.findUnique({ where: { email } });
  }

  async create(data: CreateUserDto): Promise<User> {
    return db.user.create({ data });
  }
}

Logging

Log Levels

Level Use Case
ERROR Errors and Exceptions
WARN Warning Messages
INFO Critical Operations (Login, Create, Delete)
DEBUG Debug Information

Log Examples

import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' }),
  ],
});

// 使用
logger.info('User created', { userId: user.id, email: user.email });
logger.error('Database connection failed', { error: err.message });

Performance Optimization

Database Query Optimization

  • Use indexes to speed up queries
  • Avoid N+1 query problems
  • Use JOINs instead of multiple queries
  • Paginate large datasets

Caching Strategy

import Redis from 'ioredis';

const redis = new Redis();

async function getUserWithCache(id: string): Promise<User> {
  // 尝试从缓存获取
  const cached = await redis.get(`user:${id}`);
  if (cached) {
    return JSON.parse(cached);
  }

  // 从数据库获取
  const user = await userRepository.findById(id);

  // 写入缓存(5 分钟过期)
  await redis.setex(`user:${id}`, 300, JSON.stringify(user));

  return user;
}

Connection Pool Management

  • Configure a reasonable database connection pool size
  • Release connections promptly
  • Monitor connection pool usage

Implementation Checklist

Before Implementing an API:

  • Read architecture.md §5 API Design
  • Confirm request/response format conventions
  • Confirm authentication and authorization approach
  • Explore existing code patterns in the project

After Implementing an API:

  • API endpoints conform to contract definitions
  • Implement request validation
  • Implement unified error handling
  • Add authentication and authorization
  • TDD: Each Service/Controller has a failing test first, RED verified
  • Write unit tests (Service layer)
  • Write integration tests (API endpoints)
  • Write E2E tests (complete flow)
  • Add logging
  • Code passes Lint checks