📎 Webclip
Build and test a blazing fast JSON API with Phoenix, an Elixir framework
The post walks through building a JSON API for contacts with Elixir and Phoenix. It starts from a failing test, adds an Ecto model and migration, then wires the route, controller, and view so Phoenix returns JSON and the test passes.
Reading notes#
- Phoenix is presented as an Elixir framework for fast, low-latency web applications, with response times often measured in microseconds.
- The example app is called HelloPhoenix and serves a list of contacts through
/api/contacts. - The first step is a controller test that wraps Ecto calls in a transaction so the database stays empty for each test run.
- The test inserts a
Contact, sends a request, and checks that the response status is 200 and the body matches the encoded JSON. - Running the test reveals that the
Contactstruct does not exist yet, so the model must be created. - Ecto is used with Postgres through a repository, and the article says to verify the database settings in
config/dev.exsandconfig/test.exs. - The article creates the development and test databases with
mix ecto.createandenv MIX_ENV=test mix ecto.create. - The
Contactschema definesnameandphone, and the migration creates acontactstable with those fields and timestamps. - The route is added under
/api, using JSON acceptance andresources "/contacts", ContactController. - The controller fetches all contacts with
Repo.all(Contact)and renders them withrender conn, contacts: contacts. - A
ContactViewdefinesrender("index.json", %{contacts: contacts})and returns the contacts array so Phoenix can encode it as JSON. - The article then moves some shared aliases and test helpers into
HelloPhoenix.ExUnit.CaseTemplateso tests can reuse them throughHelloPhoenix.Case. - It ends by noting that the app can be deployed to Heroku with the Elixir buildpack.
