Learn how to build JSON APIs in Phoenix with proper data exposure and error handling
Learn how to build JSON APIs in Phoenix with proper data exposure and error handling.
/api
scope to your router (with an API pipeline)render(conn, "index.json", assigns)
*_json.ex
, returning a map instead of HEEx templates@derive {Jason.Encoder, only: [:field1, :field2]}
attribute in your schema to specify which fields are exposed in your APImix phx.gen.json ContextName SchemaName table_name field:type ...
for scaffolding full CRUD APIsmix phx.gen.json Promotions Promotion promotions name code:unique
/api
scopedata
function in your JSON view to hide or compute fields, e.g.,
def data(promotion), do: %{id: promotion.id, code: promotion.code, display_name: "#{promotion.name} - #{promotion.code}"}
mix phx.new my_app --no-assets --no-live
This lesson shows how to craft JSON APIs in Phoenix—either by hand or with scaffolding generators, properly control what’s exposed, and handle API errors cleanly. You’ll see how to bootstrap both mixed and pure API-only Phoenix projects with best practices.