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
1---
2name: phoenix-api-gen
3description: 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.
4metadata:
5 source: https://skillmd.com/skills/modbender/phoenix-api-gen
6---
7
8# Phoenix API Generator
9
10## Workflow
11
12### From OpenAPI YAML
13
141. Parse the OpenAPI spec — extract paths, schemas, request/response bodies.
152. Map each schema to an Ecto schema + migration.
163. Map each path to a controller action; group by resource context.
174. Generate auth plugs from `securitySchemes`.
185. Generate ExUnit tests covering happy path + validation errors.
19
20### From Natural Language
21
221. Extract resources, fields, types, and relationships from the description.
232. Infer context boundaries (group related resources).
243. Generate schemas, migrations, controllers, views, router, and tests.
254. Ask the user to confirm before writing files.
26
27## File Generation Order
28
291. Migrations (timestamps prefix: `YYYYMMDDHHMMSS`)
302. Ecto schemas + changesets
313. Context modules (CRUD functions)
324. Controllers + FallbackController
335. JSON renderers (Phoenix 1.7+ `*JSON` modules, or `*View` for older)
346. Router scope + pipelines
357. Auth plugs
368. Tests + factories
37
38## Phoenix Conventions
39
40See [references/phoenix-conventions.md](references/phoenix-conventions.md) for project structure, naming, context patterns.
41
42Key rules:
43- One context per bounded domain (e.g., `Accounts`, `Billing`, `Notifications`).
44- Context is the public API — controllers never call Repo directly.
45- Schemas live under contexts: `MyApp.Accounts.User`.
46- Controllers delegate to contexts; return `{:ok, resource}` or `{:error, changeset}`.
47- Use `FallbackController` with `action_fallback/1` to handle error tuples.
48
49## Ecto Patterns
50
51See [references/ecto-patterns.md](references/ecto-patterns.md) for schema, changeset, migration details.
52
53Key rules:
54- Always use `timestamps(type: :utc_datetime_usec)`.
55- Binary IDs: `@primary_key {:id, :binary_id, autogenerate: true}` + `@foreign_key_type :binary_id`.
56- Separate `create_changeset/2` and `update_changeset/2` when create/update fields differ.
57- Validate required fields, formats, and constraints in changesets — not in controllers.
58
59## Multi-Tenancy
60
61Add `tenant_id :binary_id` to every tenant-scoped table. Pattern:
62
63```elixir
64# In context
65def list_resources(tenant_id) do
66 Resource
67 |> where(tenant_id: ^tenant_id)
68 |> Repo.all()
69end
70
71# In plug — extract tenant from conn and assign
72defmodule MyAppWeb.Plugs.SetTenant do
73 import Plug.Conn
74 def init(opts), do: opts
75 def call(conn, _opts) do
76 tenant_id = get_req_header(conn, "x-tenant-id") |> List.first()
77 assign(conn, :tenant_id, tenant_id)
78 end
79end
80```
81
82Always add a composite index on `[:tenant_id, <resource_id or lookup field>]`.
83
84## Auth Plugs
85
86### API Key
87
88```elixir
89defmodule MyAppWeb.Plugs.ApiKeyAuth do
90 import Plug.Conn
91 def init(opts), do: opts
92 def call(conn, _opts) do
93 with [key] <- get_req_header(conn, "x-api-key"),
94 {:ok, account} <- Accounts.authenticate_api_key(key) do
95 assign(conn, :current_account, account)
96 else
97 _ -> conn |> send_resp(401, "Unauthorized") |> halt()
98 end
99 end
100end
101```
102
103### Bearer Token
104
105```elixir
106defmodule MyAppWeb.Plugs.BearerAuth do
107 import Plug.Conn
108 def init(opts), do: opts
109 def call(conn, _opts) do
110 with ["Bearer " <> token] <- get_req_header(conn, "authorization"),
111 {:ok, claims} <- MyApp.Token.verify(token) do
112 assign(conn, :current_user, claims)
113 else
114 _ -> conn |> send_resp(401, "Unauthorized") |> halt()
115 end
116 end
117end
118```
119
120## Router Structure
121
122```elixir
123scope "/api/v1", MyAppWeb do
124 pipe_through [:api, :authenticated]
125
126 resources "/users", UserController, except: [:new, :edit]
127 resources "/teams", TeamController, except: [:new, :edit] do
128 resources "/members", MemberController, only: [:index, :create, :delete]
129 end
130end
131```
132
133## Test Generation
134
135See [references/test-patterns.md](references/test-patterns.md) for ExUnit, Mox, factory patterns.
136
137Key rules:
138- Use `async: true` on all tests that don't share state.
139- Use `Ecto.Adapters.SQL.Sandbox` for DB isolation.
140- Factory module using `ex_machina` or hand-rolled `build/1`, `insert/1`.
141- Test contexts and controllers separately.
142- For controllers: test status codes, response body shape, and error cases.
143- Mock external services with `Mox` — define behaviours, set expectations in test.
144
145### Controller Test Template
146
147```elixir
148defmodule MyAppWeb.UserControllerTest do
149 use MyAppWeb.ConnCase, async: true
150
151 import MyApp.Factory
152
153 setup %{conn: conn} do
154 user = insert(:user)
155 conn = put_req_header(conn, "authorization", "Bearer #{token_for(user)}")
156 {:ok, conn: conn, user: user}
157 end
158
159 describe "index" do
160 test "lists users", %{conn: conn} do
161 conn = get(conn, ~p"/api/v1/users")
162 assert %{"data" => users} = json_response(conn, 200)
163 assert is_list(users)
164 end
165 end
166
167 describe "create" do
168 test "returns 201 with valid params", %{conn: conn} do
169 params = params_for(:user)
170 conn = post(conn, ~p"/api/v1/users", user: params)
171 assert %{"data" => %{"id" => _}} = json_response(conn, 201)
172 end
173
174 test "returns 422 with invalid params", %{conn: conn} do
175 conn = post(conn, ~p"/api/v1/users", user: %{})
176 assert json_response(conn, 422)["errors"] != %{}
177 end
178 end
179end
180```
181
182## JSON Renderer (Phoenix 1.7+)
183
184```elixir
185defmodule MyAppWeb.UserJSON do
186 def index(%{users: users}), do: %{data: for(u <- users, do: data(u))}
187 def show(%{user: user}), do: %{data: data(user)}
188
189 defp data(user) do
190 %{
191 id: user.id,
192 email: user.email,
193 inserted_at: user.inserted_at
194 }
195 end
196end
197```
198
199## Checklist Before Writing
200
201- [ ] Migrations use `timestamps(type: :utc_datetime_usec)`
202- [ ] Binary IDs configured if project uses UUIDs
203- [ ] Tenant scoping applied where needed
204- [ ] Auth plug wired in router pipeline
205- [ ] FallbackController handles `{:error, changeset}` and `{:error, :not_found}`
206- [ ] Tests cover 200, 201, 404, 422 status codes
207- [ ] Factory defined for each schema