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
- Parse the OpenAPI spec — extract paths, schemas, request/response bodies.
- Map each schema to an Ecto schema + migration.
- Map each path to a controller action; group by resource context.
- Generate auth plugs from
securitySchemes.
- Generate ExUnit tests covering happy path + validation errors.
From Natural Language
- Extract resources, fields, types, and relationships from the description.
- Infer context boundaries (group related resources).
- Generate schemas, migrations, controllers, views, router, and tests.
- Ask the user to confirm before writing files.
File Generation Order
- Migrations (timestamps prefix:
YYYYMMDDHHMMSS)
- Ecto schemas + changesets
- Context modules (CRUD functions)
- Controllers + FallbackController
- JSON renderers (Phoenix 1.7+
*JSON modules, or *View for older)
- Router scope + pipelines
- Auth plugs
- 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
Source: modbender/skill-library-mcp — distributed by TomeVault.
1---2name: modbender-skill-library-mcp-phoenix-api-gen3description: ---4---5---6name: phoenix-api-gen7description: 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.8---910# Phoenix API Generator1112## Workflow1314### From OpenAPI YAML15161. Parse the OpenAPI spec — extract paths, schemas, request/response bodies.172. Map each schema to an Ecto schema + migration.183. Map each path to a controller action; group by resource context.194. Generate auth plugs from `securitySchemes`.205. Generate ExUnit tests covering happy path + validation errors.2122### From Natural Language23241. Extract resources, fields, types, and relationships from the description.252. Infer context boundaries (group related resources).263. Generate schemas, migrations, controllers, views, router, and tests.274. Ask the user to confirm before writing files.2829## File Generation Order30311. Migrations (timestamps prefix: `YYYYMMDDHHMMSS`)322. Ecto schemas + changesets333. Context modules (CRUD functions)344. Controllers + FallbackController355. JSON renderers (Phoenix 1.7+ `*JSON` modules, or `*View` for older)366. Router scope + pipelines377. Auth plugs388. Tests + factories3940## Phoenix Conventions4142See [references/phoenix-conventions.md](references/phoenix-conventions.md) for project structure, naming, context patterns.4344Key rules:45- One context per bounded domain (e.g., `Accounts`, `Billing`, `Notifications`).46- Context is the public API — controllers never call Repo directly.47- Schemas live under contexts: `MyApp.Accounts.User`.48- Controllers delegate to contexts; return `{:ok, resource}` or `{:error, changeset}`.49- Use `FallbackController` with `action_fallback/1` to handle error tuples.5051## Ecto Patterns5253See [references/ecto-patterns.md](references/ecto-patterns.md) for schema, changeset, migration details.5455Key rules:56- Always use `timestamps(type: :utc_datetime_usec)`.57- Binary IDs: `@primary_key {:id, :binary_id, autogenerate: true}` + `@foreign_key_type :binary_id`.58- Separate `create_changeset/2` and `update_changeset/2` when create/update fields differ.59- Validate required fields, formats, and constraints in changesets — not in controllers.6061## Multi-Tenancy6263Add `tenant_id :binary_id` to every tenant-scoped table. Pattern:6465```elixir66# In context67def list_resources(tenant_id) do68 Resource69 |> where(tenant_id: ^tenant_id)70 |> Repo.all()71end7273# In plug — extract tenant from conn and assign74defmodule MyAppWeb.Plugs.SetTenant do75 import Plug.Conn76 def init(opts), do: opts77 def call(conn, _opts) do78 tenant_id = get_req_header(conn, "x-tenant-id") |> List.first()79 assign(conn, :tenant_id, tenant_id)80 end81end82```8384Always add a composite index on `[:tenant_id, <resource_id or lookup field>]`.8586## Auth Plugs8788### API Key8990```elixir91defmodule MyAppWeb.Plugs.ApiKeyAuth do92 import Plug.Conn93 def init(opts), do: opts94 def call(conn, _opts) do95 with [key] <- get_req_header(conn, "x-api-key"),96 {:ok, account} <- Accounts.authenticate_api_key(key) do97 assign(conn, :current_account, account)98 else99 _ -> conn |> send_resp(401, "Unauthorized") |> halt()100 end101 end102end103```104105### Bearer Token106107```elixir108defmodule MyAppWeb.Plugs.BearerAuth do109 import Plug.Conn110 def init(opts), do: opts111 def call(conn, _opts) do112 with ["Bearer " <> token] <- get_req_header(conn, "authorization"),113 {:ok, claims} <- MyApp.Token.verify(token) do114 assign(conn, :current_user, claims)115 else116 _ -> conn |> send_resp(401, "Unauthorized") |> halt()117 end118 end119end120```121122## Router Structure123124```elixir125scope "/api/v1", MyAppWeb do126 pipe_through [:api, :authenticated]127128 resources "/users", UserController, except: [:new, :edit]129 resources "/teams", TeamController, except: [:new, :edit] do130 resources "/members", MemberController, only: [:index, :create, :delete]131 end132end133```134135## Test Generation136137See [references/test-patterns.md](references/test-patterns.md) for ExUnit, Mox, factory patterns.138139Key rules:140- Use `async: true` on all tests that don't share state.141- Use `Ecto.Adapters.SQL.Sandbox` for DB isolation.142- Factory module using `ex_machina` or hand-rolled `build/1`, `insert/1`.143- Test contexts and controllers separately.144- For controllers: test status codes, response body shape, and error cases.145- Mock external services with `Mox` — define behaviours, set expectations in test.146147### Controller Test Template148149```elixir150defmodule MyAppWeb.UserControllerTest do151 use MyAppWeb.ConnCase, async: true152153 import MyApp.Factory154155 setup %{conn: conn} do156 user = insert(:user)157 conn = put_req_header(conn, "authorization", "Bearer #{token_for(user)}")158 {:ok, conn: conn, user: user}159 end160161 describe "index" do162 test "lists users", %{conn: conn} do163 conn = get(conn, ~p"/api/v1/users")164 assert %{"data" => users} = json_response(conn, 200)165 assert is_list(users)166 end167 end168169 describe "create" do170 test "returns 201 with valid params", %{conn: conn} do171 params = params_for(:user)172 conn = post(conn, ~p"/api/v1/users", user: params)173 assert %{"data" => %{"id" => _}} = json_response(conn, 201)174 end175176 test "returns 422 with invalid params", %{conn: conn} do177 conn = post(conn, ~p"/api/v1/users", user: %{})178 assert json_response(conn, 422)["errors"] != %{}179 end180 end181end182```183184## JSON Renderer (Phoenix 1.7+)185186```elixir187defmodule MyAppWeb.UserJSON do188 def index(%{users: users}), do: %{data: for(u <- users, do: data(u))}189 def show(%{user: user}), do: %{data: data(user)}190191 defp data(user) do192 %{193 id: user.id,194 email: user.email,195 inserted_at: user.inserted_at196 }197 end198end199```200201## Checklist Before Writing202203- [ ] Migrations use `timestamps(type: :utc_datetime_usec)`204- [ ] Binary IDs configured if project uses UUIDs205- [ ] Tenant scoping applied where needed206- [ ] Auth plug wired in router pipeline207- [ ] FallbackController handles `{:error, changeset}` and `{:error, :not_found}`208- [ ] Tests cover 200, 201, 404, 422 status codes209- [ ] Factory defined for each schema210211---212> Source: [modbender/skill-library-mcp](https://github.com/modbender/skill-library-mcp) — distributed by [TomeVault](https://tomevault.io).213<!-- tomevault:4.0:skill_md:2026-06-15 -->