Command Palette

Search for a command to run...

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

api-builder

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

Generate complete FastAPI backend scaffolds from OpenAPI 3.x specifications. Automatically creates SQLAlchemy models, Pydantic schemas, FastAPI routers, CRUD…

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

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

API Builder

从 OpenAPI 3.x 规范自动生成完整的 FastAPI 后端脚手架,包括数据库模型、API 路由、测试和 Next.js client。

工作流程

阶段 1:验证输入

  1. 获取 OpenAPI Spec

    • 询问用户提供 OpenAPI spec:
      • 文件路径(.yaml 或 .json)
      • 粘贴 spec 内容(保存为临时文件)
      • URL(如果可访问,先下载)
  2. 验证 Spec 格式

    • 运行 scripts/validate_spec.py:
      python3 ${CLAUDE_PLUGIN_ROOT}/scripts/validate_spec.py <spec-file>
      
    • 检查 exit code:0=成功,1=失败

    如果验证失败:停止并告知用户具体错误,询问是否修正

  3. 选择生成范围

    • 运行 scripts/parse_openapi.py 查看可用 endpoints:
      python3 ${CLAUDE_PLUGIN_ROOT}/scripts/parse_openapi.py <spec-file>
      
    • 询问用户:
      • 生成全部 endpoints?
      • 只生成特定的endpoints?(让用户选择,使用 --resources 参数)

阶段 2:检测现有项目结构

  1. 检查是否为现有项目

    • 查找 app/ 或 src/ 目录
    • 检查 pyproject.toml
    • 检查是否已有 database.py、routers/、models/ 等
  2. 确定集成策略

    • 如果是现有项目:
      • 复用现有的 database.py
      • 检查文件冲突(如 app/routers/users.py 已存在)
      • 询问用户如何处理冲突:覆盖/合并/重命名/跳过
    • 如果是新项目:
      • 从 assets/fastapi-template/ 复制基础结构
      • 创建完整的项目脚手架

阶段 3:生成后端代码

使用 CLI 脚本(推荐):

运行完整的生成流程:

cd ${CLAUDE_PLUGIN_ROOT}/scripts
python3 cli.py \
  --spec <spec-file> \
  --output <output-dir> \
  [--resources users,posts]  # 可选:只生成特定资源

生成内容:

  • models/ - SQLAlchemy 数据库模型
  • schemas/ - Pydantic API schemas
  • routers/ - FastAPI 路由
  • __init__.py - 包初始化文件
  • parsed.json - 解析后的 spec 数据

关键点:

  • 脚本自动处理类型映射(参考 references/type-mapping.md)
  • 使用 Jinja2 模板(assets/templates/)生成代码
  • 生成的代码包含 TODO comments 标记业务逻辑部分
  • 添加时间戳字段(created_at, updated_at)
  • Email 字段自动添加 unique 和 index

手动步骤执行(高级):

如果需要更细粒度控制,可分步执行:

cd ${CLAUDE_PLUGIN_ROOT}/scripts

# 1. 解析 spec
python3 parse_openapi.py <spec-file> --output parsed.json

# 2. 生成代码
python3 generate_code.py \
  --parsed-data parsed.json \
  --output-dir <output-dir> \
  --templates-dir ${CLAUDE_PLUGIN_ROOT}/assets/templates

参考文档:

  • references/type-mapping.md - 类型映射规则
  • references/fastapi-patterns.md - FastAPI 最佳实践

3.5 更新 Main.py

如果不存在 app/main.py,创建它:

  • 从 assets/fastapi-template/app/main.py 复制基础结构
  • 注册所有生成的 routers
  • 配置 CORS 中间件
  • 添加根路由

如果已存在,询问用户是否添加新的 router 注册代码。

3.6 配置和运行数据库迁移(可选)

使用 CLI(推荐):

# 自动配置并运行迁移
cd ${CLAUDE_PLUGIN_ROOT}/scripts
python3 cli.py \
  --spec <spec-file> \
  --output <output-dir> \
  --setup-alembic \
  --run-migrations

手动执行:

如果用户想手动控制:

# 1. 配置 Alembic
cd ${CLAUDE_PLUGIN_ROOT}/scripts
python3 cli.py --spec <spec-file> --output <output-dir> --setup-alembic

# 2. 进入项目目录手动运行迁移
cd <output-dir>
alembic revision --autogenerate -m "Initial tables"
alembic upgrade head

生成内容:

  • alembic.ini - Alembic 配置文件
  • alembic/env.py - 迁移环境配置
  • alembic/versions/ - 迁移文件目录
  • alembic/script.py.mako - 迁移模板

何时使用迁移:

  • 全新项目:使用 --setup-alembic --run-migrations 立即创建数据库
  • 已有项目更新schema:手动运行 alembic revision --autogenerate
  • 生产环境:先测试迁移,再手动应用

阶段 4:生成测试

4.1 更新 conftest.py

  • 检查 tests/conftest.py 是否存在
  • 如果不存在,从 assets/fastapi-template/tests/conftest.py 复制
  • 为每个资源添加 fixtures:
    • sample_{resource}_data
    • create_sample_{resource}
  • 使用 assets/templates/conftest_fixture.py.j2 模板

4.2 生成 API 集成测试

  • 使用 assets/templates/test_api.py.j2 模板
  • 生成到 tests/test_api/test_{resource}_api.py
  • 包含测试:
    • CRUD 操作(create, get, update, delete)
    • 错误处理(404, 400, 422)
    • 分页、验证

参考:references/testing-patterns.md

4.3 生成 CRUD 单元测试

  • 使用 assets/templates/test_crud.py.j2 模板
  • 生成到 tests/test_crud/test_{resource}_crud.py

阶段 5:生成 Next.js Client(可选)

询问用户是否需要生成 Next.js TypeScript client。

如果需要:

使用 CLI(推荐):

cd ${CLAUDE_PLUGIN_ROOT}/scripts
python3 cli.py \
  --spec <spec-file> \
  --output <backend-output-dir> \
  --generate-client \
  [--client-output <frontend-path>/api-client.ts]

单独生成Client:

cd ${CLAUDE_PLUGIN_ROOT}/scripts
python3 generate_client.py \
  --parsed-data parsed.json \
  --output <client-output-file>

生成内容:

  • TypeScript接口定义(从OpenAPI schemas)
  • API调用方法(从OpenAPI paths)
  • ApiClient类(包含错误处理)
  • 便捷的函数导出

参考:references/type-mapping.md 的 TypeScript 映射

生成的client使用示例:

// Next.js App Router
import { apiClient } from '@/lib/api/api-client'

export default async function Page() {
  const users = await apiClient.list_users()
  return <div>{users.map(u => <div>{u.name}</div>)}</div>
}

阶段 6:验证和测试

  1. 安装依赖:

    uv add fastapi sqlalchemy alembic pydantic[email] python-multipart
    uv add --dev pytest pytest-cov httpx
    
  2. 运行类型检查:

    mypy app/
    

    如果有错误,修复后重新检查。

  3. 运行迁移:

    alembic upgrade head
    
  4. 运行测试:

    pytest tests/ -v
    

    目标:所有测试通过

  5. 手动验证:

阶段 7:完成

  1. 生成总结文档:

    • 列出所有生成的文件
    • 标记需要用户补充的 TODO 项
    • 提供下一步指南
  2. TODO 清单:

    • 实现业务逻辑(routers 中的 TODO comments)
    • 添加认证/授权
Полный SKILL.md на GitHub

Установить api-builder в Claude Code и Claude Desktop

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

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

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

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

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

Без ограничений — скилл может использовать любой инструмент.

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

metadata.json

FAQ

Что делает скилл api-builder?

Generate complete FastAPI backend scaffolds from OpenAPI 3.x specifications. Automatically creates SQLAlchemy models, Pydantic schemas, FastAPI routers, CRUD operations, database migrations, pytest tests, and Next.js TypeScript clients. Use when user provides an OpenAPI/OpenSpec file (.yaml/.json) or pastes spec content, and wants to generate API code. Triggers on phrases like "generate API from spec", "build backend from OpenAPI", "create FastAPI from this spec", "implement these endpoints", or when user shares OpenAPI specification files. Supports Python 3.12+, FastAPI, SQLite, SQLAlchemy, Alembic, pytest, and Next.js App Router.

Как установить скилл api-builder?

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

Скилл api-builder запускает скрипты?

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

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

Сравнить api-builder с