18. 17
4.WebアプリからDB操作する
マイグレーションの結果、テーブル追加されるので、確認します
# sudo -u postgres psql
psql (9.3.18)
Type "help" for help.
postgres=# c app_dev
You are now connected to database “app_dev" as user "postgres".
app_dev=# d posts
Table "public.posts"
Column | Type | Modifiers
-------------+-----------------------------+----------------------------------------------------
id | integer | not null default nextval('posts_id_seq'::regclass)
title | character varying(255) |
body | text |
inserted_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
Indexes:
"posts_pkey" PRIMARY KEY, btree (id)
23. 22
5.JSON APIを作ってみる
JSON APIも、前述したWebアプリとほぼ同じ手順で作れます
まずJSON API用のPhoenixプロジェクトを作成します
モデルを格納するDBを作成します
JSON API用のモデル生成を行います (違いはjson指定のみ)
前述のWeb用のモデルと全く同じモデルで作ってみます
# mix phx.new api --no-brunch
# cd api
# mix phx.gen.json Tool Post posts title:string body:text
…
Add the resource to your api scope in lib/api_web/router.ex:
resources "/posts", PostController, except: [:new, :edit]
Remember to update your repository by running migrations:
$ mix ecto.migrate
# mix ecto.create
24. 23
5.JSON APIを作ってみる
web/router.exへのパス追加を行います
同時に、CSRFを防止する部分も解除しておきます
モデルのマイグレーションを行います
# mix ecto.migrate
defmodule ApiWeb.Router do
use ApiWeb, :router
pipeline :browser do
…
plug :fetch_flash
# plug :protect_from_forgery
plug :put_secure_browser_headers
…
scope "/", ApiWeb do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
resources "/posts", PostController, except: [:new, :edit]
end
…
end
CSRF(cross-site request forgeries)の防止
が行われると、CSRFトークン(csrf_token)を渡さ
ないとアクセスできなくなるため解除する
※ステートレスなREST APIでの本CSRF対策は実装が難しい
25. 24
5.JSON APIを作ってみる
マイグレーションの結果、テーブル追加されるので、確認します
# sudo -u postgres psql
psql (9.3.18)
Type "help" for help.
postgres=# c api_dev
You are now connected to database “api_dev" as user "postgres".
web_dev=# d posts
Table "public.posts"
Column | Type | Modifiers
-------------+-----------------------------+----------------------------------------------------
id | integer | not null default nextval('posts_id_seq'::regclass)
title | character varying(255) |
body | text |
inserted_at | timestamp without time zone | not null
updated_at | timestamp without time zone | not null
Indexes:
"posts_pkey" PRIMARY KEY, btree (id)