164.WebアプリからDB操作するマイグレーションの結果、テーブル追加されるので、確認します# sudo -upostgres psqlpsql (9.3.16)Type "help" for help.postgres=# ¥c web_devYou are now connected to database "web_dev" as user "postgres".web_dev=# ¥d postsTable "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 nullupdated_at | timestamp without time zone | not nullIndexes:"posts_pkey" PRIMARY KEY, btree (id)
215.JSON APIを作ってみるJSON APIも、前述したWebアプリとほぼ同じ手順で作れますまずJSONAPI用のPhoenixプロジェクトを作成しますモデルを格納するDBを作成しますJSON API用のモデル生成を行います (違いはjson指定のみ)前述のWeb用のモデルと全く同じモデルで作ってみます# mix phoenix.new api --no-brunch# cd api# mix phoenix.gen.json Post posts title:string body:text…Add the resource to your api scope in web/router.ex:resources "/posts", PostController, except: [:new, :edit]Remember to update your repository by running migrations:$ mix ecto.migrate# mix ecto.create
235.JSON APIを作ってみるマイグレーションの結果、テーブル追加されるので、確認します# sudo-u postgres psqlpsql (9.3.16)Type "help" for help.postgres=# ¥c api_devYou are now connected to database “api_dev" as user "postgres".web_dev=# ¥d postsTable "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 nullupdated_at | timestamp without time zone | not nullIndexes:"posts_pkey" PRIMARY KEY, btree (id)
25.
245.JSON APIを作ってみるJSON API用のコマンドとして、どのようなものが用意されたかは、以下で確認できます一覧取得(index)は、/postsへのGETで行いますアイテム登録 (create)は、/postsへのPOSTで行います各アイテム取得 (show)は、/posts/1、/posts/2等のID指定でのGETで取得でき、アイテム更新 (update)はID指定のPUTもしくはPATCH、アイテム削除 (delete)はID指定でのDELETEで行います# mix phoenix.routespage_path GET / Api.PageController :indexpost_path GET /posts Api.PostController :indexpost_path GET /posts/:id Api.PostController :showpost_path POST /posts Api.PostController :createpost_path PATCH /posts/:id Api.PostController :updatePUT /posts/:id Api.PostController :updatepost_path DELETE /posts/:id Api.PostController :delete