Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Routing, Controllers and Plugs

Building JSON APIs and Fallback Controllers

Build a JSON API in Phoenix with the api pipeline, JSON modules, status codes, action_fallback and consistent error responses, plus CORS and versioning notes.

Phoenix is as good at JSON APIs as it is at HTML pages. An API needs the same router and controllers but different output: JSON bodies, status codes instead of redirects and a consistent error format. This lesson builds that: the :api pipeline, controller actions that return JSON, fallback controllers that keep actions short, and a few production tips.

You should know controllers and params and resources.

Phoenix code is read-only here. The JavaScript TryIts model the JSON rendering and fallback idea.

The API scope

ELIXIR
scope "/api", BlogWeb do
  pipe_through :api

  resources "/posts", PostController, except: [:new, :edit]
end

An API has no new or edit forms, so exclude them. The :api pipeline is plug :accepts, ["json"], with no session or CSRF. To create a JSON-only project use mix phx.new blog --no-html, or generate one resource with mix phx.gen.json Blog Post posts title:string body:text.

JSON modules

Modern Phoenix controllers declare their formats and put JSON rendering in a module named after the controller:

ELIXIR
defmodule BlogWeb.PostController do
  use BlogWeb, :controller

  action_fallback BlogWeb.FallbackController

  def index(conn, _params) do
    render(conn, :index, posts: Blog.Posts.list_posts())
  end

  def create(conn, %{"post" => params}) do
    with {:ok, post} <- Blog.Posts.create_post(params) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", ~p"/api/posts/#{post}")
      |> render(:show, post: post)
    end
  end

  def show(conn, %{"id" => id}) do
    with {:ok, post} <- Blog.Posts.fetch_post(id) do
      render(conn, :show, post: post)
    end
  end
end

defmodule BlogWeb.PostJSON do
  def index(%{posts: posts}), do: %{data: for(post <- posts, do: data(post))}
  def show(%{post: post}), do: %{data: data(post)}

  defp data(post) do
    %{id: post.id, title: post.title, body: post.body}
  end
end

render(conn, :index, posts: posts) calls PostJSON.index/1 with the assigns map and encodes the returned map to JSON. Building the map yourself means you decide exactly which fields leave the server: never encode a whole struct, which would leak columns such as password hashes.

Fallback controllers

Notice that create has no case for the error branch. The with expression returns the first non-matching value, such as {:error, changeset}, and action_fallback hands it to the fallback controller:

ELIXIR
defmodule BlogWeb.FallbackController do
  use BlogWeb, :controller

  def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
    conn
    |> put_status(:unprocessable_entity)
    |> put_view(json: BlogWeb.ChangesetJSON)
    |> render(:error, changeset: changeset)
  end

  def call(conn, {:error, :not_found}) do
    conn
    |> put_status(:not_found)
    |> put_view(json: BlogWeb.ErrorJSON)
    |> render(:"404")
  end

  def call(conn, {:error, :unauthorized}) do
    conn |> put_status(:unauthorized) |> put_view(json: BlogWeb.ErrorJSON) |> render(:"401")
  end
end

Every error path now has one home, so every endpoint answers errors in the same shape. Context functions just return tagged tuples ({:error, :not_found}) and never know about HTTP.

Status codes to remember

Code Use
200 OK Successful read or update
201 Created After create, with a location header
204 No Content After a delete (send_resp(conn, 204, ""))
400 Bad Request Malformed request
401 / 403 Not logged in / not allowed
404 Not Found Missing record
422 Unprocessable Entity Validation errors
429 Too Many Requests Rate limited

Errors for the changeset

ELIXIR
defmodule BlogWeb.ChangesetJSON do
  def error(%{changeset: changeset}) do
    %{errors: Ecto.Changeset.traverse_errors(changeset, &translate_error/1)}
  end

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

A failed post then returns {"errors": {"title": ["can't be blank"]}}, a shape any client can show next to the right field.

Versioning, CORS and security

  • Versioning: scope "/api/v1" keeps old clients working when you change the format.
  • CORS: browsers calling your API from another origin need CORS headers; add the cors_plug package in the endpoint, listing the allowed origins explicitly.
  • Auth: APIs usually use tokens in an authorization header; see the authentication chapter for tokens and plugs.
  • Pagination: accept page and page_size, cap the size on the server and include meta in the response.

Rendering JSON, modeled

JS Whitelisting fields in a JSON view

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

No output.

The hash never appears because the view lists fields explicitly, the same discipline as in PostJSON.data/1.

A fallback controller, modeled

JS with + action_fallback

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

No output.

Each action contains only the happy path; the wrapper plays the role of action_fallback.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does action_fallback do?

    When an action returns something that is not a conn, Phoenix calls the fallback controller's call/2 with it.
  2. 2. Which status code is right after a successful POST that creates a record?

    201 Created, usually with a location header pointing to the new resource.
  3. 3. Why build the JSON map by hand instead of encoding the struct?

    Whitelisting fields prevents leaking sensitive columns such as password hashes.
  4. 4. What status do validation errors usually get?

    422 Unprocessable Entity tells the client the data was understood but invalid.

Summary

  • JSON APIs use the :api pipeline, resources without new/edit, and PostJSON modules that build maps.
  • with plus action_fallback keeps actions to the happy path and gives every error one format.
  • Return tagged tuples from contexts; map them to status codes in the fallback controller.
  • Whitelist output fields, version your routes, configure CORS explicitly and cap pagination.

Next: HEEx templates: the basics