Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 38 ยท Projects and Practice

Project: A JSON Notes API

Build a token-protected JSON API in Phoenix: routes, a context with ownership checks, JSON views, FallbackController errors, pagination, filtering and tests.

APIs are where Phoenix is quietly excellent: tiny controllers, clear errors and very fast responses. In this project you build a notes API for authenticated users. It has create, list, show, update and delete, with ownership checks, validation errors in JSON, search, pagination and tests. It combines routing, JSON and fallback controllers, token authentication and testing.

Phoenix cannot run on this site, so the Elixir code is read-only. The runnable editors rebuild the key behaviour in JavaScript: ownership, pagination and the error format.

The contract first

Decide what clients will see before writing code.

Request Success Failure
GET /api/notes?q=milk&page=2 200 with data list and meta 401 without a token
POST /api/notes 201 with the note 422 with errors
GET /api/notes/:id 200 with the note 404 (also for other users' notes)
PUT /api/notes/:id 200 404 or 422
DELETE /api/notes/:id 204 404

Returning 404 for someone else's note, rather than 403, avoids confirming that the note exists.

Router

ELIXIR
scope "/api", MyAppWeb do
  pipe_through :api_auth        # accepts json + the bearer-token plug
  resources "/notes", NoteController, except: [:new, :edit]
end

Context: every function takes the user

The simplest way to make ownership leaks impossible is to scope every query by the current user and never expose an unscoped get_note!/1.

ELIXIR
defmodule MyApp.Notes do
  import Ecto.Query
  alias MyApp.{Repo, Notes.Note}

  def list_notes(user, params \\ %{}) do
    page = max(to_int(params["page"], 1), 1)
    size = params["page_size"] |> to_int(20) |> min(100)

    base =
      from(n in Note, where: n.user_id == ^user.id)
      |> search(params["q"])

    total = Repo.aggregate(base, :count)
    notes = base |> order_by(desc: :inserted_at, desc: :id) |> limit(^size) |> offset(^((page - 1) * size)) |> Repo.all()
    %{notes: notes, page: page, page_size: size, total: total}
  end

  def fetch_note(user, id) do
    case Repo.get_by(Note, id: id, user_id: user.id) do
      nil -> {:error, :not_found}
      note -> {:ok, note}
    end
  end

  def create_note(user, attrs) do
    %Note{user_id: user.id} |> Note.changeset(attrs) |> Repo.insert()
  end

  def update_note(%Note{} = note, attrs), do: note |> Note.changeset(attrs) |> Repo.update()
  def delete_note(%Note{} = note), do: Repo.delete(note)

  defp search(query, nil), do: query
  defp search(query, ""), do: query
  defp search(query, q), do: from(n in query, where: ilike(n.title, ^"%#{escape_like(q)}%"))

  defp escape_like(q), do: String.replace(q, ~r/[\\%_]/, "\\\\\\0")
  defp to_int(nil, default), do: default
  defp to_int(v, default) do
    case Integer.parse(to_string(v)) do
      {n, ""} -> n
      _ -> default
    end
  end
end

Details that matter: the page size is capped (no ?page_size=1000000), user_id is set from the token and never cast from params (a client cannot create a note for someone else), and the LIKE wildcards in the search term are escaped.

Controller, JSON view and fallback

ELIXIR
defmodule MyAppWeb.NoteController do
  use MyAppWeb, :controller
  action_fallback MyAppWeb.FallbackController
  alias MyApp.Notes

  def index(conn, params) do
    result = Notes.list_notes(conn.assigns.current_user, params)
    render(conn, :index, result: result)
  end

  def show(conn, %{"id" => id}) do
    with {:ok, note} <- Notes.fetch_note(conn.assigns.current_user, id) do
      render(conn, :show, note: note)
    end
  end

  def create(conn, %{"note" => attrs}) do
    with {:ok, note} <- Notes.create_note(conn.assigns.current_user, attrs) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", ~p"/api/notes/#{note.id}")
      |> render(:show, note: note)
    end
  end

  def delete(conn, %{"id" => id}) do
    with {:ok, note} <- Notes.fetch_note(conn.assigns.current_user, id),
         {:ok, _} <- Notes.delete_note(note) do
      send_resp(conn, :no_content, "")
    end
  end
end
ELIXIR
defmodule MyAppWeb.NoteJSON do
  def index(%{result: r}) do
    %{data: Enum.map(r.notes, &data/1), meta: %{page: r.page, page_size: r.page_size, total: r.total}}
  end
  def show(%{note: note}), do: %{data: data(note)}
  defp data(n), do: %{id: n.id, title: n.title, body: n.body, inserted_at: n.inserted_at}
end
ELIXIR
defmodule MyAppWeb.FallbackController do
  use MyAppWeb, :controller

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

  def call(conn, {:error, %Ecto.Changeset{} = cs}) do
    errors = Ecto.Changeset.traverse_errors(cs, fn {msg, opts} ->
      Regex.replace(~r"%{(\w+)}", msg, fn _, key -> opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() end)
    end)
    conn |> put_status(:unprocessable_entity) |> json(%{errors: errors})
  end
end

The with in each action passes any non-matching value, like {:error, :not_found}, straight to the fallback controller. Actions stay on the happy path.

Tests

ELIXIR
test "a user cannot read another user's note", %{conn: conn, user: user} do
  other = user_fixture()
  note = note_fixture(other, title: "secret")

  conn = conn |> put_bearer(user) |> get(~p"/api/notes/#{note.id}")
  assert json_response(conn, 404)
end

test "create validates", %{conn: conn, user: user} do
  conn = conn |> put_bearer(user) |> post(~p"/api/notes", note: %{title: ""})
  assert %{"errors" => %{"title" => ["can't be blank"]}} = json_response(conn, 422)
end

Runnable models

First, the context's rules: scoping by user, a capped page size and the 404-for-other-users behaviour.

Node.js Scoped notes with pagination (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Second, the with plus fallback pattern: the action only handles success, and anything else is converted to a status and an error body in one place.

Node.js with + FallbackController (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercises

  1. Add tags with a many-to-many table and a ?tag=work filter (see associations).
  2. Add cursor pagination (?after=<id>) and compare it with offset pagination on a large table.
  3. Add an ETag or updated_at check so PUT fails with 409 if the note changed since the client read it.
  4. Document the API with an OpenAPI file (the open_api_spex library is the usual choice).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does user_id come from conn.assigns.current_user instead of the request params?

    Identity must come from the verified token, never from data the client controls.
  2. 2. What does action_fallback do?

    When a with chain falls through, the fallback controller turns the error into a response.
  3. 3. Why return 404 for another user's note instead of 403?

    A 403 would confirm that the id exists. Scoped lookups simply fail to find it.
  4. 4. Why cap page_size?

    Unbounded parameters are a denial-of-service risk.

Summary

  • Design the API contract (statuses, error format) before coding.
  • Scope every query by the current user and take identity from the token.
  • Use with plus action_fallback to keep actions short and errors consistent.
  • Cap pagination, escape search wildcards and test the security boundaries.

Next: Practice, Review and Next Steps