Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Routing, Controllers and Plugs

Controllers, Params and Responses

Write Phoenix controller actions: read path, query and body params, pattern match them, render pages, redirect, set status codes, put flash messages and use sessions.

A controller is a module whose public functions, called actions, answer requests. Each action receives the conn and a map of params, does some work (usually by calling a context) and returns the conn with a response: a rendered page, a redirect or JSON. Controllers should stay thin. They translate between HTTP and your domain code and nothing more.

This lesson covers params, rendering, redirects, status codes, flash messages and sessions. You will use the router from the previous lesson.

A controller

ELIXIR
defmodule BlogWeb.PostController do
  use BlogWeb, :controller

  alias Blog.Posts

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

  def show(conn, %{"id" => id}) do
    post = Posts.get_post!(id)
    render(conn, :show, post: post)
  end
end

use BlogWeb, :controller imports Plug.Conn, the render helpers and ~p. render(conn, :index, posts: posts) looks for the BlogWeb.PostHTML module (a template folder post_html/) and calls index.html.heex with @posts available. We cover templates in HEEx templates.

Params

The second argument merges three sources into one map with string keys:

  1. Path params: /posts/42 gives "id" => "42".
  2. Query string: /posts?page=2&sort=title gives "page" => "2", "sort" => "title".
  3. Body: a form or JSON payload, parsed by Plug.Parsers in the endpoint.

Everything arrives as text. Pattern match the keys you need and convert explicitly, or let Ecto's cast convert for you:

ELIXIR
def index(conn, params) do
  page = params |> Map.get("page", "1") |> String.to_integer()
  ...
end

String.to_integer/1 raises on bad input like "abc", which would become a 500. For user-supplied values prefer Integer.parse/1:

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

Nested form fields arrive as nested maps: a form with post[title] produces %{"post" => %{"title" => "Hi"}}, which you match directly:

ELIXIR
def create(conn, %{"post" => post_params}) do
  case Posts.create_post(post_params) do
    {:ok, post} ->
      conn
      |> put_flash(:info, "Post created.")
      |> redirect(to: ~p"/posts/#{post}")

    {:error, %Ecto.Changeset{} = changeset} ->
      render(conn, :new, changeset: changeset)
  end
end

This is the standard Phoenix shape: a case on {:ok, _} or {:error, changeset}. On success redirect (the Post/Redirect/Get pattern avoids double submission on refresh); on failure re-render the form with errors.

Never pass raw params into Repo.insert or Map.put blindly. Always go through a changeset's cast, which whitelists the fields a user may set. Otherwise someone can submit is_admin=true.

Responses

Function Result
render(conn, :show, post: post) Renders a template with assigns
redirect(conn, to: ~p"/posts") 302 redirect to a local path
redirect(conn, external: "https://example.com") Redirect to another site
text(conn, "ok") Plain text body
json(conn, %{ok: true}) JSON body
send_resp(conn, 204, "") Any status and body
put_status(conn, :not_found) Sets status, chain before render
send_file(conn, 200, "path") Streams a file

redirect(to:) only accepts paths beginning with /, which protects you from open redirects. Use external: deliberately and never with unchecked user input.

ELIXIR
def show(conn, %{"id" => id}) do
  case Posts.get_post(id) do
    nil ->
      conn
      |> put_status(:not_found)
      |> put_view(html: BlogWeb.ErrorHTML)
      |> render("404.html")

    post ->
      render(conn, :show, post: post)
  end
end

Flash and session

Flash messages live for exactly one redirect: set them with put_flash(conn, :info, "Saved"), and the layout shows them on the next page. The session is a signed cookie by default for storing small values such as a user id:

ELIXIR
conn
|> put_session(:user_id, user.id)
|> configure_session(renew: true)    # new session id after login

get_session(conn, :user_id) reads it back. Session cookies are signed and encrypted using secret_key_base, but keep them small (about 4 KB) and never store secrets in them.

Assigns

assign(conn, :page_title, "Posts") stores data for templates and later plugs. In templates it appears as @page_title. Passing keyword assigns to render/3 does the same.

Params and responses, modeled

JS Merging path, query and body params

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

No output.

Path params win over query params in the merge, just like Phoenix. The parsePage helper plays the part of Integer.parse/1 with a safe fallback.

JS The create action shape

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type are the keys and values of controller params?

    Request data is text. Keys are strings, and numbers must be converted explicitly or by a changeset.
  2. 2. Why redirect after a successful create?

    Post/Redirect/Get means a page reload repeats a harmless GET, not the POST.
  3. 3. Which keeps users from setting fields like is_admin?

    cast only copies whitelisted fields, so extra params are ignored.
  4. 4. How long does a flash message last?

    Flash is stored in the session for the next request and then cleared.

Summary

  • Actions take (conn, params) and return a conn; params use string keys and arrive as text.
  • Pattern match the params you need; convert safely with Integer.parse/1 or let changesets cast.
  • Respond with render, redirect, json, text or send_resp, setting status with put_status.
  • Use flash for one-time messages and the session for small per-user state; never trust raw params.

Next: Plugs in depth