Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 48 ยท Real-World Elixir

Phoenix: Web Applications

Meet Phoenix, the Elixir web framework: how a request flows through the endpoint, router, plugs and controllers, HEEx templates and contexts.

Phoenix is the web framework most Elixir developers use. It is built on the same ideas as the rest of the language: a request is just data that flows through a series of small functions, each returning a new version of it. Because every request runs in its own lightweight process, Phoenix handles many connections at once without special effort.

In this lesson you will follow a request from the endpoint through the router, plugs and a controller to a HEEx template, and see how contexts keep business logic out of the web layer. You should know functions and modules, maps and structs and Ecto.

Phoenix is a Hex package and needs a full Elixir installation, which this site does not have. All Elixir and HEEx snippets are read-only; they follow the structure of current Phoenix releases, but generator output differs a little between versions. The JavaScript TryIts are stand-ins that show how a plug pipeline and a router work.

Creating a project

Install the generator once and create an app:

Terminal
mix archive.install hex phx_new
mix phx.new my_app
cd my_app
mix ecto.create
mix phx.server

The server starts on http://localhost:4000. The generator creates a Mix project (see Mix projects) with two main folders inside lib/: my_app/, which holds the business logic, and my_app_web/, which holds everything about the web. Keeping them apart is the central design rule of Phoenix.

The journey of a request

One request, five stops

Endpoint Starts the pipeline and handles static files.
Router Picks a controller action by method and path.
Plugs Small steps that read or change the request.
Controller Calls your logic and chooses a response.

Each stop passes the connection to the next.

1 / 2

Everything in this flow works on one struct, %Plug.Conn{}, called the conn. It holds the request (method, path, headers, params) and, as it travels, the response you are building (status, headers, body). Since data is immutable, each plug returns a new conn.

Plugs

A plug is the building block: either a function that takes a conn and options and returns a conn, or a module with init/1 and call/2.

ELIXIR
defmodule MyAppWeb.Plugs.RequestId do
  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do
    id = Base.encode16(:crypto.strong_rand_bytes(4))
    conn
    |> put_resp_header("x-request-id", id)
    |> assign(:request_id, id)
  end
end

assign/3 stores data in conn.assigns for later steps, and put_resp_header/3 sets a response header. A plug can also stop the pipeline by sending a response and calling halt/1, for example an authentication plug that returns 401 when no user is signed in.

Plugs are a pipeline in disguise, which makes them easy to model in plain JavaScript:

JS A plug pipeline with halt

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

No output.

The router

The router maps HTTP method and path to a controller function. Routes are grouped into pipelines (lists of plugs) and scopes:

ELIXIR
defmodule MyAppWeb.Router do
  use MyAppWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", MyAppWeb do
    pipe_through :browser

    get "/", PageController, :home
    resources "/posts", PostController
  end

  scope "/api", MyAppWeb do
    pipe_through :api

    get "/posts/:id", PostApiController, :show
  end
end

resources "/posts", PostController is a shortcut that creates the standard seven routes: index, show, new, create, edit, update and delete. Path segments starting with a colon, like :id, become params. Run mix phx.routes to print every route. Phoenix also generates verified routes with the ~p sigil, such as ~p"/posts/#{post}", which warns at compile time when a path matches no route.

JS A router matching method and path

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

No output.

Controllers and templates

A controller action takes the conn and the request params and produces a response:

ELIXIR
defmodule MyAppWeb.PostController do
  use MyAppWeb, :controller

  alias MyApp.Blog

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

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

  def create(conn, %{"post" => post_params}) do
    case Blog.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
end

Notice pattern matching in the function heads: %{"id" => id} pulls the id out of the params. Params always arrive with string keys. The case on {:ok, _} and {:error, changeset} is the same convention you met in error handling.

Views are plain modules with function components, and the template language is HEEx: HTML with embedded Elixir. A ~H sigil or a .html.heex file holds the markup:

HEEX
<h1>Posts</h1>

<ul>
  <li :for={post <- @posts}>
    <.link href={~p"/posts/#{post}"}>{post.title}</.link>
  </li>
</ul>

<p :if={@posts == []}>No posts yet.</p>

Details worth knowing:

  • @posts reads from the assigns you passed to render.
  • {...} (curly braces; older projects use <%= ... %>) inserts a value, escaped by default so user input cannot inject HTML.
  • :for and :if attributes handle loops and conditions on a tag.
  • <.link> is a function component; a name starting with a dot calls a function in the current module, and <Module.name> calls a remote one.
  • HEEx is checked at compile time for malformed HTML, which catches missing closing tags early.

Contexts: separating web from logic

A context is a module that exposes one area of your domain. The controller above calls Blog.list_posts/0, and it does not know about the database:

ELIXIR
defmodule MyApp.Blog do
  import Ecto.Query
  alias MyApp.{Repo, Blog.Post}

  def list_posts, do: Repo.all(from p in Post, order_by: [desc: p.inserted_at])
  def get_post!(id), do: Repo.get!(Post, id)

  def create_post(attrs) do
    %Post{}
    |> Post.changeset(attrs)
    |> Repo.insert()
  end
end

This gives you a public API for the domain that you can test without HTTP, and you can change the storage without touching controllers or templates. A good rule: if you would reuse the code from a script, a background job or a different interface, it belongs in a context, not in a controller.

Where to go next

Phoenix includes more than request handling. Channels and PubSub push messages to connected clients, Telemetry reports metrics, and LiveView, covered in Phoenix LiveView, builds interactive pages that keep their state on the server. When you are ready to ship, see Releases, Config and Deployment.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a plug at its simplest?

    A plug receives the %Plug.Conn{} and returns an updated one. Pipelines are just lists of plugs.
  2. 2. Why do route params like id arrive as strings in the controller?

    Request data is text. Convert it explicitly, or let Ecto's cast do it, and pattern match on string keys like %{"id" => id}.
  3. 3. What does resources "/posts", PostController create?

    It generates routes for index, show, new, create, edit, update and delete.
  4. 4. What is the main purpose of a context module such as MyApp.Blog?

    Contexts keep business rules out of controllers, so they can be tested and reused without HTTP.

Summary

  • Phoenix passes a %Plug.Conn{} through the endpoint, router pipelines, plugs and a controller action.
  • Plugs are small conn-to-conn steps; a plug can end the request with halt/1.
  • The router maps method and path to actions; resources creates the usual seven routes; ~p verifies paths at compile time.
  • Controllers pattern match on params (string keys) and render HEEx templates, which escape output by default.
  • Contexts hold your domain logic and call Ecto; the web layer only translates between HTTP and those functions.

Next: stateful, real-time pages in Phoenix LiveView.