Here is a basic working example ...
Step 1. Create a phoenix application.
e.g. exjson for ExampleJson or whatever your other name is
mix phoenix.new exjson --no-ecto --no-brunch --no-html
Step 2. Configure the router
Add this area to the web / router.ex file
scope "/api/v1", Exjson do pipe_through :api resources "/users", UserController end
Step 3: Put data accessible somewhere in the application
priv/data/MOCK_DATA.json
Step 4: Configure UserController
Think of the user controller as having several actions (functions) where the conn struct is served from your phoenix endpoint along with any parameters
defmodule Exjson.UserController do use Exjson.Web, :controller # GET http://localhost:4000/api/v1/users/ def index(conn, _params) do users = File.read!(file) |> Poison.decode!() render conn, users: users end # GET http://localhost:4000/api/v1/users/1 def show(conn, params) do users = File.read!(file) |> Poison.decode!() render conn, user: users |> Enum.find(&(&1["id"] === String.to_integer(params["id"]))) end defp file() do Path.join(:code.priv_dir(:exjson), "data/MOCK_DATA.json") end end
Step 5: Configure UserView
You can also think of representing users as functions that will appropriately display data received from the controller. In this case, you are using json data, so phoenix has some built-in functions to help with this.
defmodule Exjson.UserView do use Exjson.Web, :view def render("index.json", %{users: users}) do render_many(users, __MODULE__, "user.json") end def render("show.json", %{user: user}) do render_one(user, __MODULE__, "user.json") end def render("user.json", %{user: user}) do %{ id: user["id"], name: user["name"], email: user["email"] } end end