api-rest
БесплатноБез исполняемых скриптовНе проверенREST API conventions for Next.js App Router with Zod validation and standardized error handling. This skill should be used when creating API routes…
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
REST API Skill
Conventions and patterns for building REST APIs in Next.js App Router with type-safe validation and consistent error handling.
When to Use This Skill
- Creating new API routes
- Implementing CRUD operations
- Setting up validation with Zod
- Establishing error handling patterns
- Designing resource endpoints
Core Conventions
Resource Naming
Resources are always plural:
| Resource | Endpoint |
|---|---|
| Project | /api/projects |
| User | /api/users |
| Task | /api/tasks |
HTTP Methods
| Method | Purpose | Example |
|---|---|---|
| GET | Read | GET /api/projects |
| POST | Create | POST /api/projects |
| PATCH | Partial update | PATCH /api/projects/:id |
| PUT | Full replace | PUT /api/projects/:id |
| DELETE | Remove | DELETE /api/projects/:id |
URL Structure
/api/{resource} # Collection
/api/{resource}/{id} # Single item
/api/{resource}/{id}/{sub-resource} # Nested resource
Examples:
GET /api/projects # List all projects
POST /api/projects # Create project
GET /api/projects/123 # Get project 123
PATCH /api/projects/123 # Update project 123
DELETE /api/projects/123 # Delete project 123
GET /api/projects/123/tasks # List tasks for project 123
Directory Structure
src/app/api/
├── projects/
│ ├── route.ts # GET (list), POST (create)
│ └── [id]/
│ ├── route.ts # GET, PATCH, DELETE
│ └── tasks/
│ └── route.ts # Nested resource
├── users/
│ ├── route.ts
│ └── [id]/
│ └── route.ts
└── _lib/
├── errors.ts # Error utilities
├── validation.ts # Zod helpers
└── response.ts # Response helpers
Response Format
Success Responses
// Single resource
{
"data": {
"id": "123",
"name": "Project Alpha",
"createdAt": "2025-01-15T10:30:00Z"
}
}
// Collection
{
"data": [
{ "id": "123", "name": "Project Alpha" },
{ "id": "124", "name": "Project Beta" }
],
"meta": {
"total": 42,
"page": 1,
"pageSize": 20
}
}
// Empty success (204 No Content for DELETE)
// No body
Error Responses
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid request body",
"details": [
{ "field": "email", "message": "Invalid email format" }
]
}
}
Setup
Error Utilities
Create src/app/api/_lib/errors.ts:
import { NextResponse } from 'next/server';
import { ZodError } from 'zod';
export type ApiErrorCode =
| 'VALIDATION_ERROR'
| 'NOT_FOUND'
| 'UNAUTHORIZED'
| 'FORBIDDEN'
| 'CONFLICT'
| 'INTERNAL_ERROR';
interface ApiError {
code: ApiErrorCode;
message: string;
details?: unknown;
}
export function errorResponse(
code: ApiErrorCode,
message: string,
status: number,
details?: unknown
) {
const error: ApiError = { code, message };
if (details) error.details = details;
return NextResponse.json({ error }, { status });
}
export function validationError(error: ZodError) {
const details = error.errors.map((err) => ({
field: err.path.join('.'),
message: err.message,
}));
return errorResponse('VALIDATION_ERROR', 'Invalid request', 400, details);
}
export function notFound(resource: string) {
return errorResponse('NOT_FOUND', `${resource} not found`, 404);
}
export function unauthorized(message = 'Unauthorized') {
return errorResponse('UNAUTHORIZED', message, 401);
}
export function forbidden(message = 'Forbidden') {
return errorResponse('FORBIDDEN', message, 403);
}
export function conflict(message: string) {
return errorResponse('CONFLICT', message, 409);
}
export function internalError(message = 'Internal server error') {
return errorResponse('INTERNAL_ERROR', message, 500);
}
Validation Helpers
Create src/app/api/_lib/validation.ts:
import { z, ZodSchema, ZodError } from 'zod';
import { NextRequest } from 'next/server';
export async function parseBody<T>(
request: NextRequest,
schema: ZodSchema<T>
): Promise<{ data: T; error: null } | { data: null; error: ZodError }> {
try {
const body = await request.json();
const data = schema.parse(body);
return { data, error: null };
} catch (error) {
if (error instanceof ZodError) {
return { data: null, error };
}
throw error;
}
}
export function parseQuery<T>(
request: NextRequest,
schema: ZodSchema<T>
): { data: T; error: null } | { data: null; error: ZodError } {
try {
const params = Object.fromEntries(request.nextUrl.searchParams.entries());
const data = schema.parse(params);
return { data, error: null };
} catch (error) {
if (error instanceof ZodError) {
return { data: null, error };
}
throw error;
}
}
// Common schemas
export const paginationSchema = z.object({
page: z.coerce.numbe
Установить api-rest в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл api-rest?
REST API conventions for Next.js App Router with Zod validation and standardized error handling. This skill should be used when creating API routes, implementing CRUD operations, or establishing API patterns for a project.
Как установить скилл api-rest?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api-rest запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic