Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

08 - Phoenix crash course #8: Controllers

Learn how Phoenix controllers handle HTTP requests, process data, and render different formats

By Daniel Bergholz • Aug 19, 2025

Learn how Phoenix controllers handle HTTP requests, process data, and render different formats.

Controllers

  • Controllers are the main layer that receive HTTP requests, process data, and choose what to render (HTML, JSON, text, etc.)
  • Actions are functions inside controllers. For an action to be routable, it must take two arguments: conn (connection) and params (parameters from path or query)

Rendering output

  • Use text(conn, "plain text"), html(conn, "<h1>HTML</h1>"), or json(conn, %{map}) to return different formats directly from an action
  • Preferred: Use the render function to link an action to a view/template. The matching view module and template file must follow naming conventions

Multiple formats in one controller

  • You can return either HTML or JSON from the same action using separate view modules and templates
  • For the same endpoint (e.g., /products), append ?_format=json to request JSON instead of HTML

View file setup

  • For each controller, create matching [controller]_html.ex (for HTML) and [controller]_json.ex (for JSON) files with a function named after the action
  • For JSON, just return a map; for HTML, use HEEx templates

Best practice

  • For separation of concerns, it’s best to split APIs and HTML into different controllers and scopes when possible, but this flexible system lets you have both on the same route for reuse (e.g., web apps and mobile apps sharing endpoints)

Summary

This video explains how controllers manage requests and responses in Phoenix, render multiple formats, and structure view logic for best flexibility and maintainability.

Related

#phoenix-and-elixir #phoenix-crash-course #daniel-bergholz