Advanced topics

Books

HTTP routing

The built-in HTTP router

The router is the component in charge of translating each incoming HTTP request to an Action.

An HTTP request is seen as an event by the MVC framework. This event contains two major pieces of information:

the request path (e.g. /clients/1542, /photos/list), including the query string

the HTTP method (e.g. GET, POST, …).

Routes are defined in the conf/routes file, which is compiled. This means that you’ll see route errors directly in your browser:

The routes file syntax

conf/routes is the configuration file used by the router. This file lists all of the routes needed by the application. Each route consists of an HTTP method and URI pattern, both associated with a call to an Action generator.

Let’s see what a route definition looks like:

GET /clients/:id controllers.Clients.show(id: Long)

Each route starts with the HTTP method, followed by the URI pattern. The last element is the call definition.

Optional parameters

You can also specify an optional parameter that does not need to be present in all requests:

# The version parameter is optional. E.g. /api/list-all?version=3.0
GET /api/list-all controllers.Api.list(version: Option[String])

Routing priority

Many routes can match the same request. If there is a conflict, the first route (in declaration order) is used.

Reverse routing

The router can also be used to generate a URL from within a Scala call. This makes it possible to centralize all your URI patterns in a single configuration file, so you can be more confident when refactoring your application.

For each controller used in the routes file, the router will generate a ‘reverse controller’ in the routes package, having the same action methods, with the same signature, but returning a play.api.mvc.Call instead of a play.api.mvc.Action.

The play.api.mvc.Call defines an HTTP call, and provides both the HTTP method and the URI.