微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🔥

Elixir 全栈 API 智能脚手架

phoenix-api-gen · vv1.0.0
开发 安全 S+ 级 作者 gchapim 公开目录收录
2.3k 下载 699 安装 7.4k 收藏 25.2k 浏览

简介

基于 Phoenix 最佳实践,从 OpenAPI 或自然语言一键生成包含认证、多租户和测试的完整 Elixir REST API 代码。

原始描述

Generate a full Phoenix JSON API from an OpenAPI spec or natural language description. Creates contexts, Ecto schemas, migrations, controllers, JSON views/renderers, router entries, ExUnit tests with factories, auth plugs, and tenant scoping. Use when building a new Phoenix REST API, adding CRUD endpoints, scaffolding resources, or converting an OpenAPI YAML into a Phoenix project.

通过你的 Agent 添加

安装目录:phoenix-api-gen/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/phoenix-api-gen/
Codex CLI~/.codex/skills/phoenix-api-gen/
DeepSeek Harness~/.agents/skills/phoenix-api-gen/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心功能

Phoenix API Generator 是一个面向 Elixir/Phoenix 生态的代码生成工具,可将 OpenAPI YAML 规范或自然语言描述转换为生产就绪的 REST API 代码。其核心能力包括:

  • 双模式输入:支持解析 OpenAPI 3.x 规范,或从自然语言描述提取资源、字段和关系
  • 完整代码栈:自动生成迁移、Ecto schema、上下文模块、控制器、JSON 渲染器、路由配置、认证插件及 ExUnit 测试
  • Phoenix 最佳实践:严格遵循 Context 模式(业务逻辑与控制器分离)、FallbackController 错误处理、以及 Phoenix 1.7+ 的 *JSON 模块命名
  • 企业级特性:内置多租户支持(tenant_id 作用域)、API Key / Bearer Token 认证插件、以及工厂模式测试

显著优点

  1. 标准化输出:强制使用 timestamps(type: :utc_datetime_usec)、binary_id 主键、复合索引等 Ecto 最佳实践
  2. 安全设计:生成的认证代码遵循 Plug 规范,错误处理通过 FallbackController 统一响应
  3. 测试完备:自动生成 200/201/404/422 状态码覆盖的测试用例,支持 async: true 并行执行
  4. 可审查流程:文件写入前要求用户确认,避免意外覆盖

潜在局限

  • 语言生态绑定:仅适用于 Elixir/Phoenix 项目,无法生成其他框架代码
  • 复杂业务逻辑:生成的 Context 函数为标准的 CRUD 模板,复杂查询和业务规则仍需手动扩展
  • OpenAPI 覆盖度:极端复杂的 OpenAPI 特性(如回调、链接、高级安全方案)可能需手动调整
  • 运行时依赖:需要 Phoenix 1.5+ 和 Ecto 3.x 环境,旧版本项目兼容性有限

适用人群

  • Phoenix 新手:希望快速搭建符合社区规范的 API 骨架
  • 全栈开发者:需要将设计文档(OpenAPI)快速转化为可运行代码
  • 多租户 SaaS 团队:需要标准化租户隔离和认证流程的项目
  • 代码审查严格团队:依赖自动化生成减少代码风格争议

常规风险

  • 认证策略错配:生成的 ApiKeyAuth 和 BearerAuth 为模板实现,需根据实际 JWT 库或密钥管理方案调整
  • 租户隔离验证:tenant_id 过滤和复合索引需通过集成测试验证,避免数据越界
  • 测试覆盖盲区:生成的测试聚焦 HTTP 状态码和响应结构,业务边界条件需人工补充
  • 数据库迁移冲突:迁移文件使用 YYYYMMDDHHMMSS 时间戳前缀,在团队协作时需防范命名冲突

技能正文


name: phoenix-api-gen description: Generate a full Phoenix JSON API from an OpenAPI spec or natural language description. Creates contexts, Ecto schemas, migrations, controllers, JSON views/renderers, router entries, ExUnit tests with factories, auth plugs, and tenant scoping. Use when building a new Phoenix REST API, adding CRUD endpoints, scaffolding resources, or converting an OpenAPI YAML into a Phoenix project.

Phoenix API Generator

Workflow

From OpenAPI YAML

  1. Parse the OpenAPI spec — extract paths, schemas, request/response bodies.
  2. Map each schema to an Ecto schema + migration.
  3. Map each path to a controller action; group by resource context.
  4. Generate auth plugs from securitySchemes.
  5. Generate ExUnit tests covering happy path + validation errors.

From Natural Language

  1. Extract resources, fields, types, and relationships from the description.
  2. Infer context boundaries (group related resources).
  3. Generate schemas, migrations, controllers, views, router, and tests.
  4. Ask the user to confirm before writing files.

File Generation Order

  1. Migrations (timestamps prefix: YYYYMMDDHHMMSS)
  2. Ecto schemas + changesets
  3. Context modules (CRUD functions)
  4. Controllers + FallbackController
  5. JSON renderers (Phoenix 1.7+ *JSON modules, or *View for older)
  6. Router scope + pipelines
  7. Auth plugs
  8. Tests + factories

Phoenix Conventions

See references/phoenix-conventions.md for project structure, naming, context patterns.

Key rules:

  • One context per bounded domain (e.g., Accounts, Billing, Notifications).
  • Context is the public API — controllers never call Repo directly.
  • Schemas live under contexts: MyApp.Accounts.User.
  • Controllers delegate to contexts; return {:ok, resource} or {:error, changeset}.
  • Use FallbackController with action_fallback/1 to handle error tuples.

Ecto Patterns

See references/ecto-patterns.md for schema, changeset, migration details.

Key rules:

  • Always use timestamps(type: :utc_datetime_usec).
  • Binary IDs: @primary_key {:id, :binary_id, autogenerate: true} + @foreign_key_type :binary_id.
  • Separate create_changeset/2 and update_changeset/2 when create/update fields differ.
  • Validate required fields, formats, and constraints in changesets — not in controllers.

Multi-Tenancy

Add tenant_id :binary_id to every tenant-scoped table. Pattern:

# In context
def list_resources(tenant_id) do
  Resource
  |> where(tenant_id: ^tenant_id)
  |> Repo.all()
end

# In plug — extract tenant from conn and assign
defmodule MyAppWeb.Plugs.SetTenant do
  import Plug.Conn
  def init(opts), do: opts
  def call(conn, _opts) do
    tenant_id = get_req_header(conn, "x-tenant-id") |> List.first()
    assign(conn, :tenant_id, tenant_id)
  end
end

Always add a composite index on [:tenant_id, <resource_id or lookup field>].

Auth Plugs

API Key

defmodule MyAppWeb.Plugs.ApiKeyAuth do
  import Plug.Conn
  def init(opts), do: opts
  def call(conn, _opts) do
    with [key] <- get_req_header(conn, "x-api-key"),
         {:ok, account} <- Accounts.authenticate_api_key(key) do
      assign(conn, :current_account, account)
    else
      _ -> conn |> send_resp(401, "Unauthorized") |> halt()
    end
  end
end

Bearer Token

defmodule MyAppWeb.Plugs.BearerAuth do
  import Plug.Conn
  def init(opts), do: opts
  def call(conn, _opts) do
    with ["Bearer " <> token] <- get_req_header(conn, "authorization"),
         {:ok, claims} <- MyApp.Token.verify(token) do
      assign(conn, :current_user, claims)
    else
      _ -> conn |> send_resp(401, "Unauthorized") |> halt()
    end
  end
end

Router Structure

scope "/api/v1", MyAppWeb do
  pipe_through [:api, :authenticated]

  resources "/users", UserController, except: [:new, :edit]
  resources "/teams", TeamController, except: [:new, :edit] do
    resources "/members", MemberController, only: [:index, :create, :delete]
  end
end

Test Generation

See references/test-patterns.md for ExUnit, Mox, factory patterns.

Key rules:

  • Use async: true on all tests that don't share state.
  • Use Ecto.Adapters.SQL.Sandbox for DB isolation.
  • Factory module using ex_machina or hand-rolled build/1, insert/1.
  • Test contexts and controllers separately.
  • For controllers: test status codes, response body shape, and error cases.
  • Mock external services with Mox — define behaviours, set expectations in test.

Controller Test Template

defmodule MyAppWeb.UserControllerTest do
  use MyAppWeb.ConnCase, async: true

  import MyApp.Factory

  setup %{conn: conn} do
    user = insert(:user)
    conn = put_req_header(conn, "authorization", "Bearer #{token_for(user)}")
    {:ok, conn: conn, user: user}
  end

  describe "index" do
    test "lists users", %{conn: conn} do
      conn = get(conn, ~p"/api/v1/users")
      assert %{"data" => users} = json_response(conn, 200)
      assert is_list(users)
    end
  end

  describe "create" do
    test "returns 201 with valid params", %{conn: conn} do
      params = params_for(:user)
      conn = post(conn, ~p"/api/v1/users", user: params)
      assert %{"data" => %{"id" => _}} = json_response(conn, 201)
    end

    test "returns 422 with invalid params", %{conn: conn} do
      conn = post(conn, ~p"/api/v1/users", user: %{})
      assert json_response(conn, 422)["errors"] != %{}
    end
  end
end

JSON Renderer (Phoenix 1.7+)

defmodule MyAppWeb.UserJSON do
  def index(%{users: users}), do: %{data: for(u <- users, do: data(u))}
  def show(%{user: user}), do: %{data: data(user)}

  defp data(user) do
    %{
      id: user.id,
      email: user.email,
      inserted_at: user.inserted_at
    }
  end
end

Checklist Before Writing

  • Migrations use timestamps(type: :utc_datetime_usec)
  • Binary IDs configured if project uses UUIDs
  • Tenant scoping applied where needed
  • Auth plug wired in router pipeline
  • FallbackController handles {:error, changeset} and {:error, :not_found}
  • Tests cover 200, 201, 404, 422 status codes
  • Factory defined for each schema

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

backendapidevelopment-engineeringdatabasetestingautomationelixirphoenix

同类 Skill