Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

API Development

БесплатноБез исполняемых скриптовНе проверен

Build REST APIs with proper error handling, status codes, request validation, response formatting, and rate limiting. Apply when creating API routes, handling…

diegosouzapwот diegosouzapw★ 68 звёзд на GitHub

Об этом скилле

API Development

Systematic REST API development with error handling, validation, and consistent response formats.

Overview

This Skill enforces:

  • HTTP status codes (appropriate, not overused)
  • RFC 7807 Problem Details for errors
  • Input validation and sanitization
  • Consistent response formatting
  • Request correlation IDs
  • Rate limiting
  • Security-first error messages
  • Centralized error handling

Apply when building API routes, handling errors, or designing responses.

HTTP Status Codes

Status Code Categories

Range Purpose Common Examples
200-299 Success 200 OK, 201 Created, 204 No Content
300-399 Redirection 301 Moved Permanently, 302 Found
400-499 Client Errors 400 Bad Request, 401 Unauthorized, 404 Not Found
500-599 Server Errors 500 Internal Error, 503 Service Unavailable

Correct Status Codes

// ✅ GOOD: Specific status codes
200  // GET: Resource retrieved
201  // POST: Resource created
204  // DELETE: Resource deleted (no content)
400  // Bad Request: Validation failed
401  // Unauthorized: Not authenticated
403  // Forbidden: Authenticated but no permission
404  // Not Found: Resource doesn't exist
409  // Conflict: Duplicate email
422  // Unprocessable Entity: Semantic error
429  // Too Many Requests: Rate limited
500  // Internal Server Error: Server bug

// ❌ BAD: Vague status codes
200  // Success response for everything
500  // Error response for everything
200  // Returned even when validation failed

Error Response Format (RFC 7807)

Problem Details Structure

// RFC 7807 Problem Details
type ProblemDetails = {
  type: string;        // URL to error type documentation
  title: string;       // Short error title
  status: number;      // HTTP status code
  detail: string;      // Specific error details
  instance?: string;   // Request ID for tracking
  errors?: Record<string, string[]>;  // Field-level errors
};

Implementation

// lib/errors.ts
export class ApiError extends Error {
  constructor(
    public status: number,
    public title: string,
    public detail: string,
    public type: string = 'about:blank',
    public errors?: Record<string, string[]>
  ) {
    super(detail);
    this.name = 'ApiError';
  }

  toJSON() {
    return {
      type: this.type,
      title: this.title,
      status: this.status,
      detail: this.detail,
      instance: this.instance,
      ...(this.errors && { errors: this.errors })
    };
  }
}

Error Responses

// ✅ GOOD: RFC 7807 format
{
  "type": "https://api.example.com/errors/validation-failed",
  "title": "Validation Failed",
  "status": 400,
  "detail": "The request body contains invalid data",
  "instance": "req-12345",
  "errors": {
    "email": ["Invalid email format"],
    "age": ["Must be >= 18"]
  }
}

// ✅ GOOD: Unauthorized (no sensitive details)
{
  "type": "https://api.example.com/errors/unauthorized",
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required",
  "instance": "req-12346"
}

// ❌ BAD: Leaks internal details
{
  "error": "User not found in database",
  "stack": "Error: query failed at line 42..."
}

// ❌ BAD: Not structured
{
  "message": "Something went wrong"
}

Centralized Error Handler

// middleware/error-handler.ts
import { NextRequest, NextResponse } from 'next/server';
import { ApiError } from '@/lib/errors';

export function errorHandler(error: unknown) {
  const requestId = crypto.randomUUID();

  // Log error (internal, never exposed)
  console.error(`[${requestId}] Error:`, error);

  // ApiError (predictable)
  if (error instanceof ApiError) {
    return NextResponse.json(
      {
        type: error.type,
        title: error.title,
        status: error.status,
        detail: error.detail,
        instance: requestId,
        ...(error.errors && { errors: error.errors })
      },
      { status: error.status }
    );
  }

  // Validation error
  if (error instanceof ZodError) {
    return NextResponse.json(
      {
        type: 'https://api.example.com/errors/validation-failed',
        title: 'Validation Failed',
        status: 400,
        detail: 'The request body contains invalid data',
        instance: requestId,
        errors: error.flatten().fieldErrors
      },
      { status: 400 }
    );
  }

  // Unknown error (generic message)
  return NextResponse.json(
    {
      type: 'https://api.example.com/errors/internal-server-error',
      title: 'Internal Server Error',
      status: 500,
      detail: 'An unexpected error occurred',
      instance: requestId
    },
    { status: 500 }
  );
}

Using Error Handler

// app/api/users/route.ts
import { errorHandler } from '@/middleware/error-handler';

export async function POST(request: Request) {
  try {
    const body = await request.json();

    // Validate
    const validated = CreateUserSchema.parse(body);

    // Check duplicate
    const exis
Полный SKILL.md на GitHub

Установить API Development в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Write
Edit
Bash

Вложенные файлы

metadata.json

FAQ

Что делает скилл API Development?

Build REST APIs with proper error handling, status codes, request validation, response formatting, and rate limiting. Apply when creating API routes, handling errors, validating input, or designing API responses.

Как установить скилл API Development?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл API Development запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить API Development с