Phoenix v1.3.3 Phoenix.Router View Source

Defines a Phoenix router.

The router provides a set of macros for generating routes that dispatch to specific controllers and actions. Those macros are named after HTTP verbs. For example:

defmodule MyAppWeb.Router do
  use Phoenix.Router

  get "/pages/:page", PageController, :show
end

The get/3 macro above accepts a request of format "/pages/VALUE" and dispatches it to the show action in the PageController.

Routes can also match glob-like patterns, routing any path with a common base to the same controller. For example:

get "/dynamic*anything", DynamicController, :show

Phoenix’s router is extremely efficient, as it relies on Elixir pattern matching for matching routes and serving requests.

Helpers

Phoenix automatically generates a module Helpers inside your router which contains named helpers to help developers generate and keep their routes up to date.

Helpers are automatically generated based on the controller name. For example, the route:

get "/pages/:page", PageController, :show

will generate the following named helper:

MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello")
"/pages/hello"

MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query")
"/pages/hello?some=query"

MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello")
"http://example.com/pages/hello"

MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query")
"http://example.com/pages/hello?some=query"

If the route contains glob-like patterns, parameters for those have to be given as list:

MyAppWeb.Router.Helpers.dynamic_path(conn_or_endpoint, :show, ["dynamic", "something"])
"/dynamic/something"

The URL generated in the named URL helpers is based on the configuration for :url, :http and :https. However, if for some reason you need to manually control the URL generation, the url helpers also allow you to pass in a URI struct:

uri = %URI{scheme: "https", host: "other.example.com"}
MyAppWeb.Router.Helpers.page_url(uri, :show, "hello")
"https://other.example.com/pages/hello"

The named helper can also be customized with the :as option. Given the route:

get "/pages/:page", PageController, :show, as: :special_page

the named helper will be:

MyAppWeb.Router.Helpers.special_page_path(conn, :show, "hello")
"/pages/hello"

Scopes and Resources

It is very common in Phoenix applications to namespace all of your routes under the application scope:

scope "/", MyAppWeb do
  get "/pages/:id", PageController, :show
end

The route above will dispatch to MyApp.PageController. This syntax is not only convenient for developers, since we don’t have to repeat the MyApp. prefix on all routes, but it also allows Phoenix to put less pressure in the Elixir compiler. If instead we had written:

get "/pages/:id", MyAppWeb.PageController, :show

The Elixir compiler would infer that the router depends directly on MyApp.PageController, which is not true. By using scopes, Phoenix can properly hint to the Elixir compiler the controller is not an actual dependency of the router. This provides more efficient compilation times.

Scopes allow us to scope on any path or even on the helper name:

scope "/api/v1", MyAppWeb, as: :api_v1 do
  get "/pages/:id", PageController, :show
end

For example, the route above will match on the path "/api/v1/pages/:id" and the named route will be api_v1_page_path, as expected from the values given to scope/2 option.

Phoenix also provides a resources/4 macro that allows developers to generate “RESTful” routes to a given resource:

defmodule MyAppWeb.Router do
  use Phoenix.Router

  resources "/pages", PageController, only: [:show]
  resources "/users", UserController, except: [:delete]
end

Finally, Phoenix ships with a mix phx.routes task that nicely formats all routes in a given router. We can use it to verify all routes included in the router above:

$ mix phx.routes
page_path  GET    /pages/:id       PageController.show/2
user_path  GET    /users           UserController.index/2
user_path  GET    /users/:id/edit  UserController.edit/2
user_path  GET    /users/new       UserController.new/2
user_path  GET    /users/:id       UserController.show/2
user_path  POST   /users           UserController.create/2
user_path  PATCH  /users/:id       UserController.update/2
           PUT    /users/:id       UserController.update/2

One can also pass a router explicitly as an argument to the task:

$ mix phx.routes MyAppWeb.Router

Check scope/2 and resources/4 for more information.

Pipelines and plugs

Once a request arrives at the Phoenix router, it performs a series of transformations through pipelines until the request is dispatched to a desired end-point.

Such transformations are defined via plugs, as defined in the Plug specification. Once a pipeline is defined, it can be piped through per scope.

For example:

defmodule MyAppWeb.Router do
  use Phoenix.Router

  pipeline :browser do
    plug :fetch_session
    plug :accepts, ["html"]
  end

  scope "/" do
    pipe_through :browser

    # browser related routes and resources
  end
end

Phoenix.Router imports functions from both Plug.Conn and Phoenix.Controller to help define plugs. In the example above, fetch_session/2 comes from Plug.Conn while accepts/2 comes from Phoenix.Controller.

Note that router pipelines are only invoked after a route is found. No plug is invoked in case no matches were found.

Link to this section Summary

Functions

Generates a route to handle a connect request to the given path

Generates a route to handle a delete request to the given path

Forwards a request at the given path to a plug

Generates a route to handle a get request to the given path

Generates a route to handle a head request to the given path

Generates a route match based on an arbitrary HTTP method

Generates a route to handle a options request to the given path

Generates a route to handle a patch request to the given path

Defines a pipeline to send the connection through

Defines a plug pipeline

Defines a plug inside a pipeline

Generates a route to handle a post request to the given path

Generates a route to handle a put request to the given path

Defines “RESTful” routes for a resource

Defines a scope in which routes can be nested

Define a scope with the given path

Defines a scope with the given path and alias

Generates a route to handle a trace request to the given path

Link to this section Functions

Link to this macro connect(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a connect request to the given path.

Link to this macro delete(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a delete request to the given path.

Link to this macro forward(path, plug, plug_opts \\ [], router_opts \\ []) View Source (macro)

Forwards a request at the given path to a plug.

All paths that match the forwarded prefix will be sent to the forwarded plug. This is useful for sharing a router between applications or even breaking a big router into smaller ones. The router pipelines will be invoked prior to forwarding the connection.

The forwarded plug will be initialized at compile time.

Note, however, that we don’t advise forwarding to another endpoint. The reason is that plugs defined by your app and the forwarded endpoint would be invoked twice, which may lead to errors.

Examples

scope "/", MyApp do
  pipe_through [:browser, :admin]

  forward "/admin", SomeLib.AdminDashboard
  forward "/api", ApiRouter
end
Link to this macro get(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a get request to the given path.

Link to this macro head(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a head request to the given path.

Link to this macro match(verb, path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route match based on an arbitrary HTTP method.

Useful for defining routes not included in the builtin macros:

get, post, put, patch, delete, options, connect, trace, head

The catch-all verb, :*, may also be used to match all HTTP methods.

Examples

match(:move, "/events/:id", EventController, :move)

match(:*, "/any", SomeController, :any)
Link to this macro options(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a options request to the given path.

Link to this macro patch(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a patch request to the given path.

Link to this macro pipe_through(pipes) View Source (macro)

Defines a pipeline to send the connection through.

See pipeline/2 for more information.

Link to this macro pipeline(plug, list) View Source (macro)

Defines a plug pipeline.

Pipelines are defined at the router root and can be used from any scope.

Examples

pipeline :api do
  plug :token_authentication
  plug :dispatch
end

A scope may then use this pipeline as:

scope "/" do
  pipe_through :api
end

Every time pipe_through/1 is called, the new pipelines are appended to the ones previously given.

Link to this macro plug(plug, opts \\ []) View Source (macro)

Defines a plug inside a pipeline.

See pipeline/2 for more information.

Link to this macro post(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a post request to the given path.

Link to this macro put(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a put request to the given path.

Link to this macro resources(path, controller) View Source (macro)

See resources/4.

Link to this macro resources(path, controller, opts) View Source (macro)

See resources/4.

Link to this macro resources(path, controller, opts, list) View Source (macro)

Defines “RESTful” routes for a resource.

The given definition:

resources "/users", UserController

will include routes to the following actions:

  • GET /users => :index
  • GET /users/new => :new
  • POST /users => :create
  • GET /users/:id => :show
  • GET /users/:id/edit => :edit
  • PATCH /users/:id => :update
  • PUT /users/:id => :update
  • DELETE /users/:id => :delete

Options

This macro accepts a set of options:

  • :only - a list of actions to generate routes for, for example: [:show, :edit]
  • :except - a list of actions to exclude generated routes from, for example: [:delete]
  • :param - the name of the parameter for this resource, defaults to "id"
  • :name - the prefix for this resource. This is used for the named helper and as the prefix for the parameter in nested resources. The default value is automatically derived from the controller name, i.e. UserController will have name "user"
  • :as - configures the named helper exclusively
  • :singleton - defines routes for a singleton resource that is looked up by the client without referencing an ID. Read below for more information

Singleton resources

When a resource needs to be looked up without referencing an ID, because it contains only a single entry in the given context, the :singleton option can be used to generate a set of routes that are specific to such single resource:

  • GET /user => :show
  • GET /user/new => :new
  • POST /user => :create
  • GET /user/edit => :edit
  • PATCH /user => :update
  • PUT /user => :update
  • DELETE /user => :delete

Usage example:

resources "/account", AccountController, only: [:show], singleton: true

Nested Resources

This macro also supports passing a nested block of route definitions. This is helpful for nesting children resources within their parents to generate nested routes.

The given definition:

resources "/users", UserController do
  resources "/posts", PostController
end

will include the following routes:

user_post_path  GET     /users/:user_id/posts           PostController :index
user_post_path  GET     /users/:user_id/posts/:id/edit  PostController :edit
user_post_path  GET     /users/:user_id/posts/new       PostController :new
user_post_path  GET     /users/:user_id/posts/:id       PostController :show
user_post_path  POST    /users/:user_id/posts           PostController :create
user_post_path  PATCH   /users/:user_id/posts/:id       PostController :update
                PUT     /users/:user_id/posts/:id       PostController :update
user_post_path  DELETE  /users/:user_id/posts/:id       PostController :delete
Link to this macro scope(options, list) View Source (macro)

Defines a scope in which routes can be nested.

Examples

scope path: "/api/v1", as: :api_v1, alias: API.V1 do
  get "/pages/:id", PageController, :show
end

The generated route above will match on the path "/api/v1/pages/:id" and will dispatch to :show action in API.V1.PageController. A named helper api_v1_page_path will also be generated.

Options

The supported options are:

  • :path - a string containing the path scope
  • :as - a string or atom containing the named helper scope
  • :alias - an alias (atom) containing the controller scope
  • :host - a string containing the host scope, or prefix host scope, ie "foo.bar.com", "foo."
  • :private - a map of private data to merge into the connection when a route matches
  • :assigns - a map of data to merge into the connection when a route matches
Link to this macro scope(path, options, list) View Source (macro)

Define a scope with the given path.

This function is a shortcut for:

scope path: path do
  ...
end

Examples

scope "/api/v1", as: :api_v1, alias: API.V1 do
  get "/pages/:id", PageController, :show
end
Link to this macro scope(path, alias, options, list) View Source (macro)

Defines a scope with the given path and alias.

This function is a shortcut for:

scope path: path, alias: alias do
  ...
end

Examples

scope "/api/v1", API.V1, as: :api_v1 do
  get "/pages/:id", PageController, :show
end
Link to this macro trace(path, plug, plug_opts, options \\ []) View Source (macro)

Generates a route to handle a trace request to the given path.