Skip to content

Instantly share code, notes, and snippets.

@FL4TLiN3
Last active October 23, 2015 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FL4TLiN3/2c8b8e9bbb98f89d74f8 to your computer and use it in GitHub Desktop.
Save FL4TLiN3/2c8b8e9bbb98f89d74f8 to your computer and use it in GitHub Desktop.
[Elixir] PhoenixでJSONを返すWeb APIを作る ref: http://qiita.com/FL4TLiN3/items/41ca80cdbfca1956ed78
mix phoenix.gen.html Note notes title:string description:text
curl 'http://localhost:4000/api/notes' -v -X GET -H 'Accept: application/json'
#(該当箇所のみ抜粋)
def index(conn, _params) do
notes = Repo.all(Note)
# render(conn, "index.html", notes: notes)
render(conn, :index, notes: notes)
end
defmodule Demo.NoteView do
use Demo.Web, :view
def render("index.json", %{notes: notes}) do
%{data: render_many(notes, Demo.NoteView, "note.json")}
end
def render("show.json", %{story: story}) do
%{data: render_one(note, Demo.NoteView, "note.json")}
end
def render("note.json", %{note: note}) do
%{id: note.id,
title: note.title,
description: note.description}
end
end
defmodule Demo.Router do
use Demo.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", Smaug do
pipe_through :browser
get "/", PageController, :index
resources "/notes", NoteController
end
scope "/api", Smaug do
pipe_through :api
resources "/notes", NoteController, only: [:index, :show]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment