3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

3秒で作るElixirのJsonAPI

Last updated at Posted at 2020-05-16

はじめに

ちょっと前に,ElixirでJSONを返すかんたんなAPIを作成しようと思ったときにエラーに悩まされた覚えがあったので書き留めておきます。

1秒: プロジェクト作成

プロジェクトを作成します。

mix phx.new jsonsan --no-ecto

Fetch and install dependencies? [Yn]はもちろんYにします。
インストールが完了したら,

cd jsonsan
mix phx.server

でサーバーが起動すると思います。
今回はライブラリを使用しません。

2秒: コントローラー作成

とりあえず適当なコントローラーを作成します。

jsonsan_web/controllers/data_controller.ex
defmodule JsonsanWeb.DataController do
  use JsonsanWeb, :controller

  def index(conn, _params) do
    msg = "PA PA YA!!"
    json(conn, %{message: msg})
  end
end

json()を使ってJSONを返します。

3秒: ルーティング設定

さっき作った関数を,router.exから呼び出します。

jsonsan_web/router.ex
defmodule JsonsanWeb.Router do
  use JsonsanWeb, :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 "/", JsonsanWeb do
    pipe_through :browser

    get "/", PageController, :index
  end

  # Other scopes may use custom stacks.
  scope "/api", JsonsanWeb do
    pipe_through :api

    post "/", DataController, :index
  end
end

scope "/api"と書いてあるところが,最初はコメントアウトしてあると思います。
この部分のコメントアウトを外して,DataControllerを呼び出すようにします。

動作確認

さて,それでは mix phx.serverをして,postリクエストを送信してJSONが返ってくるかを確認します。
image.png

今回は僕はpostmanで確認しました。
無事にJSONが返ってきています!!

おわり

はじめてapiをelixirで作ろうと思ったときに,put_flushがどうとかと言ったエラーが全然わからなかった覚えがあったので,また作り方を忘れてしまったらこの記事を見て思い出そうと思います。

ありがとうございました。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?