concept api in category elixir

appears as: pi, n API, Api
Phoenix in Action

This is an excerpt from Manning's book Phoenix in Action.

Listing 3.2. The BlogWeb.Router module (lib/blog_web/router.ex)
defmodule BlogWeb.Router do
  use BlogWeb, :router

  pipeline :browser do                         #1
    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 "/", BlogWeb do                        #2
    pipe_through :browser

    get "/", PageController, :index
    resources "/posts", PostController do
      resources "/comments", CommentController, only: [:create]
    end
  end

  scope "/api", BlogWeb.API do
    pipe_through :api

    resources "/posts", PostController, only: [:index, :show]
  end
end

Most APIs are expected to return something other than HTML—typically XML or JSON (though many other formats are also used). In the router.ex file, you’ll likely notice that another pipeline is already set up for JSON. This pipeline is a great starting point for an API—all it does is set itself up for accepting json requests. The pipeline already has the name of :api.

Listing 13.2. The api pipeline
defmodule AuctionWeb.Router do
  use AuctionWeb, :router
  # ...
  pipeline :api do
    plug :accepts, ["json"]       #1
  end
  # ...
end

If you compare the pipelines for :api and :browser, you’ll notice that :browser does a lot of stuff that :api doesn’t. fetch_session, fetch_flash, protect_from_forgery, and put_secure_browser_headers are all browser-specific plugs that you won’t need when forming a JSON response. The final plug (AuctionWeb.Authenticator) is one you created yourself. The API won’t be returning any private information and will be read-only, so you don’t need to do any authentication on the request.