Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

16 - Phoenix crash course #16: JSON and APIs

Learn how to build JSON APIs in Phoenix with proper data exposure and error handling

By Daniel Bergholz • Aug 19, 2025

Learn how to build JSON APIs in Phoenix with proper data exposure and error handling.

Returning JSON from Phoenix

  • Add an /api scope to your router (with an API pipeline)
  • Create controllers that render JSON by calling render(conn, "index.json", assigns)
  • Create view modules ending in *_json.ex, returning a map instead of HEEx templates

JSON Encoding

  • Implement the @derive {Jason.Encoder, only: [:field1, :field2]} attribute in your schema to specify which fields are exposed in your API

JSON Generator

  • Use mix phx.gen.json ContextName SchemaName table_name field:type ... for scaffolding full CRUD APIs
  • Example:
    mix phx.gen.json Promotions Promotion promotions name code:unique
  • Add generated resource routes to your router /api scope

API Responses and Data Functions

  • Use a data function in your JSON view to hide or compute fields, e.g.,
    def data(promotion), do: %{id: promotion.id, code: promotion.code, display_name: "#{promotion.name} - #{promotion.code}"}

Fallback Controller

  • Handle errors globally in a dedicated fallback controller instead of cluttering each action with error checks

API-Only Phoenix Application

  • Generate a stripped-down Phoenix app for API-only use with:
    mix phx.new my_app --no-assets --no-live
  • Removes HTML, assets, live view, and extra dependencies/UI—resulting in a clean, efficient JSON API server

Testing & Docs

  • JSON generators include tests for controller and context logic, and provide examples for working with client tools (Insomnia/Postman/curl)

Summary

This lesson shows how to craft JSON APIs in Phoenix—either by hand or with scaffolding generators, properly control what’s exposed, and handle API errors cleanly. You’ll see how to bootstrap both mixed and pure API-only Phoenix projects with best practices.

Related

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