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