Agent skill

Phoenix JSON API

by j-morgan6 in j-morgan6/elixir-phoenix-guide

A skill your agent uses when building JSON API endpoints — :api pipeline, FallbackController, error rendering, pagination, versioning, Bearer auth.

MITAuto-check passedAI & LLM Engineering

Install Phoenix JSON API

skills CLI
$ npx skills add j-morgan6/elixir-phoenix-guide --skill phoenix-json-api -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install j-morgan6/elixir-phoenix-guide phoenix-json-api --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/j-morgan6/elixir-phoenix-guide.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/phoenix-json-api .claude/skills/phoenix-json-api && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
phoenix-json-api
GitHub stars
166
Token cost
~2.8k tokens
SKILL.md length
251 words
Files
1
Skills in repo
19
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses when building JSON API endpoints — :api pipeline, FallbackController, error rendering, pagination, versioning, Bearer auth.

  • Works in 7 steps: Use the :api pipeline — don't mix HTML… → Render errors as structured JSON —… → Use offset/limit for pagination — never… → …
  • Building JSON API endpoints — :api pipeline
  • SKILL.md covers RULES — Follow these with no…, API Pipeline Setup, Controller Pattern and FallbackController, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Phoenix JSON API is an agent skill from j-morgan6/elixir-phoenix-guide. Use when building JSON API endpoints — :api pipeline, FallbackController, error rendering, pagination, versioning, Bearer auth.

Its SKILL.md is about 2.8k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in AI & LLM Engineering, covering LLM observability and REST APIs. The licence is MIT.

When your agent uses it

  • Building JSON API endpoints — :api pipeline
  • FallbackController
  • Error rendering

Example prompts

  • “/phoenix-json-api”

Workflow steps

7 steps, taken from the first numbered list in SKILL.md.

  1. Use the :api pipeline — don't mix HTML and JSON pipelines; API routes skip CSRF, sessions, and browser headers
  2. Render errors as structured JSON — {:error, changeset} must become {"errors": {...}}; never return raw text or HTML errors
  3. Use offset/limit for pagination — never return unbounded collections; default to a sensible limit (e.g., 20)
  4. Version APIs via URL prefix (/api/v1/) — not headers; URL versioning is visible, cacheable, and debuggable
  5. Use FallbackController for consistent error handling — every action returns {:ok, result} or {:error, reason}; the fallback renders errors
  6. Authenticate via Bearer tokens in Authorization header — not cookies; API clients don't have browser sessions
  7. Use json/2 helper — ensures Content-Type: application/json; avoid render for simple JSON responses

What it can do on your machine

Read from SKILL.md and the folder at commit cdfddac. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are elixir and json).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Phoenix JSON API loads about 2.8k tokens when it runs. Until then it costs about 36 tokens; SKILL.md has 251 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~36
When it runs · the whole SKILL.md, loaded when a task matches
~2.8k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from j-morgan6/elixir-phoenix-guide at commit cdfddac, republished under its MIT licence (© j-morgan6). 251 words, ~2,805 tokens.

Download SKILL.mdSave it as .claude/skills/phoenix-json-api/SKILL.md (or your agent's skills folder).
name
phoenix-json-api
description
Use when building JSON API endpoints — :api pipeline, FallbackController, error rendering, pagination, versioning, Bearer auth.
file_patterns
**/*_controller.ex, **/*_json.ex, **/router.ex
auto_suggest
true

Phoenix JSON API

RULES — Follow these with no exceptions

  1. Use the :api pipeline — don't mix HTML and JSON pipelines; API routes skip CSRF, sessions, and browser headers
  2. Render errors as structured JSON — {:error, changeset} must become {"errors": {...}}; never return raw text or HTML errors
  3. Use offset/limit for pagination — never return unbounded collections; default to a sensible limit (e.g., 20)
  4. Version APIs via URL prefix (/api/v1/) — not headers; URL versioning is visible, cacheable, and debuggable
  5. Use FallbackController for consistent error handling — every action returns {:ok, result} or {:error, reason}; the fallback renders errors
  6. Authenticate via Bearer tokens in Authorization header — not cookies; API clients don't have browser sessions
  7. Use json/2 helper — ensures Content-Type: application/json; avoid render for simple JSON responses

API Pipeline Setup

elixir
# lib/my_app_web/router.ex
defmodule MyAppWeb.Router do
  use MyAppWeb, :router

  pipeline :api do
    plug :accepts, ["json"]
    # No :fetch_session, :protect_from_forgery, :put_secure_browser_headers
    # APIs use tokens, not sessions
  end

  pipeline :api_auth do
    plug MyAppWeb.Plugs.ApiAuth
  end

  # Public endpoints (no auth required)
  scope "/api/v1", MyAppWeb.API.V1, as: :api_v1 do
    pipe_through :api

    post "/auth/login", AuthController, :login
    post "/auth/register", AuthController, :register
  end

  # Protected endpoints
  scope "/api/v1", MyAppWeb.API.V1, as: :api_v1 do
    pipe_through [:api, :api_auth]

    resources "/posts", PostController, except: [:new, :edit]
    resources "/users", UserController, only: [:index, :show, :update]
  end
end

Controller Pattern

Controllers return {:ok, result} or {:error, reason} — the FallbackController handles error rendering.

elixir
defmodule MyAppWeb.API.V1.PostController do
  use MyAppWeb, :controller

  alias MyApp.Blog
  alias MyApp.Blog.Post

  action_fallback MyAppWeb.FallbackController

  def index(conn, params) do
    page =
      case Integer.parse(params["page"] || "1") do
        {n, ""} when n > 0 -> n
        _ -> 1
      end

    per_page = Map.get(params, "per_page", "20") |> String.to_integer() |> min(100)

    {posts, total} = Blog.list_posts(page: page, per_page: per_page)

    conn
    |> put_resp_header("x-total-count", to_string(total))
    |> json(%{
      data: Enum.map(posts, &post_json/1),
      meta: %{page: page, per_page: per_page, total: total}
    })
  end

  def show(conn, %{"id" => id}) do
    with {:ok, post} <- Blog.get_post(id) do
      json(conn, %{data: post_json(post)})
    end
  end

  def create(conn, %{"post" => post_params}) do
    with {:ok, %Post{} = post} <- Blog.create_post(post_params) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", ~p"/api/v1/posts/#{post}")
      |> json(%{data: post_json(post)})
    end
  end

  def update(conn, %{"id" => id, "post" => post_params}) do
    with {:ok, post} <- Blog.get_post(id),
         {:ok, %Post{} = updated} <- Blog.update_post(post, post_params) do
      json(conn, %{data: post_json(updated)})
    end
  end

  def delete(conn, %{"id" => id}) do
    with {:ok, post} <- Blog.get_post(id),
         {:ok, _} <- Blog.delete_post(post) do
      send_resp(conn, :no_content, "")
    end
  end

  defp post_json(%Post{} = post) do
    %{
      id: post.id,
      title: post.title,
      body: post.body,
      inserted_at: post.inserted_at,
      updated_at: post.updated_at
    }
  end
end

Bad:

elixir
# Mixing concerns — error handling inline, inconsistent responses
def show(conn, %{"id" => id}) do
  case Repo.get(Post, id) do
    nil -> conn |> put_status(404) |> text("Not found")
    post -> conn |> put_status(200) |> render("show.json", post: post)
  end
end

FallbackController

Centralized error handling — every error gets a consistent JSON response.

elixir
defmodule MyAppWeb.FallbackController do
  use MyAppWeb, :controller

  # Ecto changeset errors
  def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
    conn
    |> put_status(:unprocessable_entity)
    |> json(%{errors: format_changeset_errors(changeset)})
  end

  # Not found
  def call(conn, {:error, :not_found}) do
    conn
    |> put_status(:not_found)
    |> json(%{errors: %{detail: "Not found"}})
  end

  # Unauthorized — no valid credentials (401)
  def call(conn, {:error, :unauthorized}) do
    conn
    |> put_status(:unauthorized)
    |> json(%{errors: %{detail: "Unauthorized"}})
  end

  # Forbidden — authenticated, but not allowed to do this (403)
  def call(conn, {:error, :forbidden}) do
    conn
    |> put_status(:forbidden)
    |> json(%{errors: %{detail: "Forbidden"}})
  end

  # Generic error
  def call(conn, {:error, reason}) when is_binary(reason) do
    conn
    |> put_status(:bad_request)
    |> json(%{errors: %{detail: reason}})
  end

  defp format_changeset_errors(changeset) do
    Ecto.Changeset.traverse_errors(changeset, fn {msg, opts} ->
      Regex.replace(~r"%{(\w+)}", msg, fn _, key ->
        opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
      end)
    end)
  end
end

Context functions should return tagged tuples:

elixir
defmodule MyApp.Blog do
  def get_post(id) do
    case Repo.get(Post, id) do
      nil -> {:error, :not_found}
      post -> {:ok, post}
    end
  end
end

Bearer Token Authentication

elixir
defmodule MyAppWeb.Plugs.ApiAuth do
  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do
    with ["Bearer " <> token] <- get_req_header(conn, "authorization"),
         {:ok, user} <- MyApp.Accounts.verify_api_token(token) do
      assign(conn, :current_user, user)
    else
      _ ->
        conn
        |> put_status(:unauthorized)
        |> Phoenix.Controller.json(%{errors: %{detail: "Unauthorized"}})
        |> halt()
    end
  end
end

Token generation in the auth controller:

elixir
defmodule MyAppWeb.API.V1.AuthController do
  use MyAppWeb, :controller

  alias MyApp.Accounts

  def login(conn, %{"email" => email, "password" => password}) do
    case Accounts.authenticate_user(email, password) do
      {:ok, user} ->
        token = Accounts.generate_api_token(user)
        json(conn, %{data: %{token: token, user_id: user.id}})

      {:error, :invalid_credentials} ->
        conn
        |> put_status(:unauthorized)
        |> json(%{errors: %{detail: "Invalid email or password"}})
    end
  end
end

Pagination

Never return unbounded collections. Cap per_page to prevent abuse.

elixir
defmodule MyApp.Blog do
  import Ecto.Query

  def list_posts(opts \\ []) do
    page = Keyword.get(opts, :page, 1)
    per_page = Keyword.get(opts, :per_page, 20) |> min(100)
    offset = (page - 1) * per_page

    posts =
      from(p in Post,
        order_by: [desc: p.inserted_at],
        limit: ^per_page,
        offset: ^offset
      )
      |> Repo.all()

    total = Repo.aggregate(Post, :count)

    {posts, total}
  end
end

Response format:

json
{
  "data": [...],
  "meta": {
    "page": 1,
    "per_page": 20,
    "total": 142
  }
}

API Versioning

Version via URL prefix. It's visible in logs, cacheable by CDNs, and simple to implement.

elixir
# router.ex
scope "/api/v1", MyAppWeb.API.V1, as: :api_v1 do
  pipe_through [:api, :api_auth]
  resources "/posts", PostController, except: [:new, :edit]
end

# When v2 is needed, add a new scope
scope "/api/v2", MyAppWeb.API.V2, as: :api_v2 do
  pipe_through [:api, :api_auth]
  resources "/posts", PostController, except: [:new, :edit]
end

Controller directory structure:

lib/my_app_web/controllers/api/
├── v1/
│   ├── post_controller.ex
│   ├── user_controller.ex
│   └── auth_controller.ex
└── v2/
    └── post_controller.ex  # Only modules that changed

JSON Rendering

For simple responses, use json/2. For complex or reusable serialization, use JSON views.

Simple (json/2)
elixir
# Direct — good for simple responses
json(conn, %{data: %{id: post.id, title: post.title}})
JSON Views (for complex/reusable serialization)
elixir
# lib/my_app_web/controllers/api/v1/post_json.ex
defmodule MyAppWeb.API.V1.PostJSON do
  alias MyApp.Blog.Post

  def index(%{posts: posts, meta: meta}) do
    %{data: for(post <- posts, do: data(post)), meta: meta}
  end

  def show(%{post: post}) do
    %{data: data(post)}
  end

  def data(%Post{} = post) do
    %{
      id: post.id,
      title: post.title,
      body: post.body,
      author: author_data(post.author),
      inserted_at: post.inserted_at,
      updated_at: post.updated_at
    }
  end

  defp author_data(nil), do: nil
  defp author_data(author) do
    %{id: author.id, name: author.name}
  end
end

# In controller — use render with the JSON view
def show(conn, %{"id" => id}) do
  with {:ok, post} <- Blog.get_post(id) do
    render(conn, :show, post: post)
  end
end

Testing API Endpoints

elixir
defmodule MyAppWeb.API.V1.PostControllerTest do
  use MyAppWeb.ConnCase

  setup %{conn: conn} do
    user = user_fixture()
    token = MyApp.Accounts.generate_api_token(user)

    conn =
      conn
      |> put_req_header("accept", "application/json")
      |> put_req_header("authorization", "Bearer #{token}")

    %{conn: conn, user: user}
  end

  describe "GET /api/v1/posts" do
    test "lists posts with pagination", %{conn: conn} do
      for _ <- 1..25, do: post_fixture()

      conn = get(conn, ~p"/api/v1/posts?page=1&per_page=10")
      response = json_response(conn, 200)

      assert length(response["data"]) == 10
      assert response["meta"]["total"] == 25
      assert response["meta"]["page"] == 1
    end
  end

  describe "POST /api/v1/posts" do
    test "creates post with valid data", %{conn: conn} do
      attrs = %{"post" => %{"title" => "Test", "body" => "Content"}}
      conn = post(conn, ~p"/api/v1/posts", attrs)

      assert %{"data" => %{"id" => id, "title" => "Test"}} = json_response(conn, 201)
      assert get_resp_header(conn, "location") == ["/api/v1/posts/#{id}"]
    end

    test "returns errors with invalid data", %{conn: conn} do
      attrs = %{"post" => %{"title" => ""}}
      conn = post(conn, ~p"/api/v1/posts", attrs)

      assert %{"errors" => errors} = json_response(conn, 422)
      assert errors["title"] != nil
    end
  end

  describe "unauthenticated requests" do
    test "returns 401 without token" do
      conn = build_conn()
      conn = get(conn, ~p"/api/v1/posts")

      assert json_response(conn, 401)["errors"]["detail"] == "Unauthorized"
    end
  end
end

See ecto-essentials skill for query and changeset patterns. See security-essentials skill for token handling and auth security. See testing-essentials skill for comprehensive testing patterns.

© j-morgan6, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in skills/phoenix-json-api of j-morgan6/elixir-phoenix-guide.

Open the folder on GitHubat commit cdfddac

Compare with similar skills

Phoenix JSON API next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Phoenix JSON API compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Phoenix JSON API this skillj-morgan6/elixir-phoenix-guide166—~2.8kAutomated safety check: PassMIT
Databuddydatabuddy-analytics/Databuddy1.2k—~2.1kAutomated safety check: PassAGPL-3.0
Phoenix REST APIArize-ai/phoenix12k—~286Automated safety check: PassCustom licence
Backend Dev Guidelineslangfuse/langfuse36k—~1.9kAutomated safety check: PassCustom licence
Elixir Expertpass-agent/loomkin1811 repos~796Automated safety check: PassMIT
Hex Docs Searchbradleygolden/claude-marketplace-elixir176—~4.1kAutomated safety check: NotesMIT

Similar skills

  • Databuddy

    databuddy-analytics/Databuddy

    Integrate Databuddy analytics using the SDK, REST API, or MCP.

    1.2k GitHub stars~2.1k tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Phoenix REST API

    Arize-ai/phoenix

    REST API development for Phoenix. An agent skill from Arize-ai/phoenix.

    12k GitHub stars~286 tokensUpdated today
    Backend & APIsAuto-check passed
  • Backend Dev Guidelines

    langfuse/langfuse

    Build or review Langfuse backend code. An agent skill from langfuse/langfuse.

    36k GitHub stars~1.9k tokensUpdated today
    Backend & APIsAuto-check passed
  • Elixir Expert

    pass-agent/loomkin

    Expert in Elixir, Phoenix Framework, and OTP. An agent skill from pass-agent/loomkin.

    181 GitHub starsUsed in 1 repo~796 tokens
    AI & LLM EngineeringAuto-check passed
  • Hex Docs Search

    bradleygolden/claude-marketplace-elixir

    Research Hex packages (Sobelow, Phoenix, Ecto, Credo, Ash, etc).

    176 GitHub stars~4.1k tokensUpdated 8 mo ago
    AI & LLM EngineeringAuto-check: notes
  • Camera Provider Reolink

    SharpAI/DeepCamera

    Reolink camera integration — RTSP and HTTP API. An agent skill from SharpAI/DeepCamera.

    3.1k GitHub stars~329 tokensUpdated 21 days ago
    AI & LLM EngineeringAuto-check passed

More from j-morgan6/elixir-phoenix-guide

All 19 skills in this repo
  • Code Quality

    j-morgan6/elixir-phoenix-guide

    A skill your agent uses when refactoring for duplication, complexity, or dead code — includes the plugin's on-demand analysis scripts.

    166 GitHub stars~1.4k tokensUpdated 3 mo ago
    Auto-check passed
  • Deployment Gotchas

    j-morgan6/elixir-phoenix-guide

    A skill your agent uses when preparing releases or deployment config — runtime.exs vs compile-time config, release migrations, PHXHOST/PHXSERVER, assets, health checks.

    166 GitHub stars~2.6k tokensUpdated 3 mo ago
    Auto-check passed
  • Ecto Changeset Patterns

    j-morgan6/elixir-phoenix-guide

    A skill your agent uses when a resource needs multiple changesets (registration vs update), conditional validation, field transforms, or uniqueness validation — changeset composition.

    166 GitHub stars~2.1k tokensUpdated 3 mo ago
    Auto-check passed
  • Ecto Essentials

    j-morgan6/elixir-phoenix-guide

    A skill your agent uses when defining schemas, writing queries, or creating migrations — schema design, Repo usage, indexes, query composition.

    166 GitHub stars~2.2k tokensUpdated 3 mo ago
    Auto-check passed
  • Ecto Nested Associations

    j-morgan6/elixir-phoenix-guide

    A skill your agent uses when a form or operation manages parent and child records together — castassoc/castembed, onreplace, Ecto.Multi across tables, FK cascade design.

    166 GitHub stars~2.2k tokensUpdated 3 mo ago
    Auto-check passed
  • Elixir Essentials

    j-morgan6/elixir-phoenix-guide

    A skill your agent uses when writing or refactoring core Elixir — pattern matching, case/cond/with, pipes, {:ok, }/{:error, } contracts.

    166 GitHub stars~2.2k tokensUpdated 3 mo ago
    Auto-check passed

Questions about Phoenix JSON API

What does Phoenix JSON API do?

A skill your agent uses when building JSON API endpoints — :api pipeline, FallbackController, error rendering, pagination, versioning, Bearer auth. Phoenix JSON API is an agent skill from j-morgan6/elixir-phoenix-guide. Use when building JSON API endpoints — :api pipeline, FallbackController, error rendering, pagination, versioning, Bearer auth.

When should I use Phoenix JSON API?

Phoenix JSON API fits situations like: building JSON API endpoints — :api pipeline; fallbackController; error rendering.

How do I install Phoenix JSON API in Claude Code?

Run `npx skills add j-morgan6/elixir-phoenix-guide --skill phoenix-json-api -a claude-code`. Or copy the skill folder (skills/phoenix-json-api in j-morgan6/elixir-phoenix-guide) into .claude/skills/phoenix-json-api in your project. Claude Code loads it when a task matches its description.

How do I install Phoenix JSON API in Codex?

Run `npx skills add j-morgan6/elixir-phoenix-guide --skill phoenix-json-api -a codex`. Or copy the skill folder (skills/phoenix-json-api in j-morgan6/elixir-phoenix-guide) into .agents/skills/phoenix-json-api in your project. Codex loads it when a task matches its description.

Can I use Phoenix JSON API in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add j-morgan6/elixir-phoenix-guide --skill phoenix-json-api -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/phoenix-json-api, .gemini/skills/phoenix-json-api, .github/skills/phoenix-json-api and .opencode/skills/phoenix-json-api in your project.

What does Phoenix JSON API need to run?

SKILL.md names no scripts, command-line tools or credentials: Phoenix JSON API is instructions for the agent only.

Does Phoenix JSON API access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Phoenix JSON API safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Phoenix JSON API use?

Phoenix JSON API is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Phoenix JSON API use?

About 2.8k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Phoenix JSON API?

Skills that share tags, products or a category with Phoenix JSON API: Databuddy (databuddy-analytics/Databuddy, 1.2k stars), Phoenix REST API (Arize-ai/phoenix, 12k stars), Backend Dev Guidelines (langfuse/langfuse, 36k stars) and Elixir Expert (pass-agent/loomkin, 181 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Phoenix JSON API?

j-morgan6 (a GitHub user) maintains it in j-morgan6/elixir-phoenix-guide, which has 166 GitHub stars. The repository holds 19 skills in this directory. The repository was last updated on July 6, 2026.

Source: j-morgan6/elixir-phoenix-guide on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.