Last active
October 23, 2015 09:51
-
-
Save FL4TLiN3/2c8b8e9bbb98f89d74f8 to your computer and use it in GitHub Desktop.
[Elixir] PhoenixでJSONを返すWeb APIを作る ref: http://qiita.com/FL4TLiN3/items/41ca80cdbfca1956ed78
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mix phoenix.gen.html Note notes title:string description:text |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
curl 'http://localhost:4000/api/notes' -v -X GET -H 'Accept: application/json' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#(該当箇所のみ抜粋) | |
def index(conn, _params) do | |
notes = Repo.all(Note) | |
# render(conn, "index.html", notes: notes) | |
render(conn, :index, notes: notes) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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