Elixir Phoenix REST API
backend
Elixir
scaffolding
zen
Build a scalable REST API with Phoenix framework and Ecto for database operations.
By chris_d
12/8/2025
Prompt
Elixir Phoenix REST API
Build a scalable REST API for [Application] using Phoenix framework with Ecto for database operations.
Requirements
1. API Endpoints
Create RESTful endpoints for:
- [Resource 1] - CRUD operations (e.g., users)
- [Resource 2] - CRUD operations (e.g., posts)
- [Resource 3] - CRUD operations (e.g., comments)
2. Database Schema
Define Ecto schemas for:
- Data models with types
- Associations/relationships
- Validations
- Changesets
3. Business Logic
Implement:
- Context modules for business logic
- Pure functions
- Pattern matching
- Error handling with {:ok, _} and {:error, _}
4. JSON API
Handle:
- JSON serialization
- Request parsing
- Response formatting
- Status codes
5. Features
Add:
- Authentication (optional)
- Pagination
- Filtering
- Error handling
- Input validation
Implementation Pattern
# lib/[app]_web/router.ex
defmodule [App]Web.Router do
use [App]Web, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/api", [App]Web do
pipe_through :api
resources "/[resources]", [Resource]Controller
end
end
# lib/[app]/[domain]/[resource].ex - Schema
defmodule [App].[Domain].[Resource] do
use Ecto.Schema
import Ecto.Changeset
schema "[resources]" do
field :[field1], :string
field :[field2], :integer
field :[field3], :boolean, default: false
# Associations
belongs_to :[parent], [App].[Domain].[Parent]
has_many :[children], [App].[Domain].[Child]
timestamps()
end
def changeset(user, attrs) do
user
|> cast(attrs, [:name, :email, :age])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> unique_constraint(:email)
end
end
Context
# lib/my_app/accounts.ex
defmodule MyApp.Accounts do
alias MyApp.Repo
alias MyApp.Accounts.User
def list_users do
Repo.all(User)
end
def get_user!(id), do: Repo.get!(User, id)
def create_user(attrs \\\\ %{}) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
end
View
# lib/my_app_web/views/user_view.ex
defmodule MyAppWeb.UserView do
use MyAppWeb, :view
def render("index.json", %{users: users}) do
%{data: render_many(users, __MODULE__, "user.json")}
end
def render("show.json", %{user: user}) do
%{data: render_one(user, __MODULE__, "user.json")}
end
def render("user.json", %{user: user}) do
%{
id: user.id,
name: user.name,
email: user.email
}
end
end
Tags
elixir
phoenix
api
functional
Tested Models
gpt-4
claude-3-opus