F6.02 · part 1 of 3
Routes & verbs
A route is a single, declarative line that says “this verb and this path run that action.”
get "/courses/:id", CourseController, :show reads as: a GET to a path with
an :id segment dispatches to CourseController.show/2, with the
segment delivered in the action’s params. Phoenix gives you the HTTP verbs directly
(get, post, put,
delete), resources for the seven RESTful routes of a noun, and
live to point a URL at a LiveView. And because routes are compiled, the
~p sigil checks every path you build against the router at compile time — a typo
in a link is a warning, not a 404 in production.
See the four route kinds, read a route’s anatomy part by part, then a real router. Each route still ends at a thin controller that calls the facade.
Four kinds of route
Most routes are a verb pointed at an action. resources expands into the standard
seven for a noun, and live hands the connection to a LiveView instead of a controller.
Select a kind to see what it does.
Route kinds · select one
kind: get
maps: read → an action
Reach for the plain verb first; it is the clearest mapping from a request to your code.
resources is a shorthand worth using only when a noun really has the full set of
actions.
A route, part by part
Every route is the same four parts in the same order: the verb, the path (with any
:segments that become params), the controller module, and the action atom. Read left
to right, a route is a sentence.
get · /courses/:id · CourseController · :show
The :id segment is the join to the engine: it arrives in the action’s
params, becomes the branded id you pass to a facade call, and is decoded by the same Portal.ID
from F4 and F5.
A real router
A handful of routes covers the platform’s read and write paths, plus one live route for the interactive
enrollment screen built later. Verified ~p paths build URLs that the compiler checks
against these routes, so a renamed path breaks the build, not the page.
scope "/", PortalWeb do pipe_through :browser get "/courses", CourseController, :index # list get "/courses/:id", CourseController, :show # one — :id is a param post "/enroll", EnrollmentController, :create # write resources "/lessons", LessonController, only: [:show] live "/enroll/:id", EnrollmentLive # a LiveView (F6.06) end # verified ~p paths are checked against the router at compile time def course_path(course), do: ~p"/courses/#{course.id}" # typo => compile warning
a verb and a path
Declared once in the router — the only place an action is named.
a checked link
~p builds URLs the compiler verifies against these routes.
Next: pipelines & scopes
— the pipe_through :browser line above is the stack of plugs that runs before any
of these actions.
References
Primary sources for this lesson, and where it connects in the course.
Sources
- Routing — Phoenix documentation — verbs, paths, and scopes.
- Controllers — Phoenix documentation — actions and rendering.
Plug— documentation — the composable middleware spec.