Skip to Content
Course content

76: Play Framework Routing

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I once worked with a developer who spent an entire Tuesday afternoon hunting down a series of 404 errors that only appeared in the production environment. He had renamed a critical endpoint from /user/profile to /account/settings in the routes file, but he had hardcoded the old URL strings in about fifteen different Twirl templates. Since those were just strings, the Scala compiler didn't say a word. The app built perfectly, deployed successfully, and then proceeded to break every single user link on the profile page. It was a classic "string-typing" disaster.

That's exactly why the Play Framework handles routing the way it does. It isn't just a configuration file; it's a source for code generation. When you define your routes, Play generates a "Reverse Router" that allows you to create URLs as typed function calls. If you change a route and your code still compiles, you can be reasonably sure you haven't broken your internal links.

The Anatomy of the Routes File

The conf/routes file is where the magic happens. It uses a specific DSL (Domain Specific Language) to map an HTTP method and a URI pattern to a specific method in one of your controllers. Let's look at a real-world example for a simple project management tool:

GET     /projects              controllers.ProjectController.listProjects
GET     /projects/:projectId     controllers.ProjectController.showProject(id: Long)
POST    /projects                controllers.ProjectController.createProject
GET     /projects/:projectId/tasks controllers.TaskController.listTasks(projectId: Long)

Notice the :projectId syntax. That's a dynamic path parameter. Play extracts whatever value is in that position of the URL and passes it directly into the controller method. I've found that being explicit about types here—like (id: Long)—is a lifesaver. If a user tries to visit /projects/abc, Play will automatically return a 400 Bad Request because "abc" isn't a Long, saving you from writing tedious validation logic inside your controller.

Avoiding the String Trap with Reverse Routing

As I mentioned with my colleague's 404 nightmare, you should almost never write <a href="/projects/123"> in your templates. Instead, you use the Reverse Router. Play generates an object that mirrors your routes file, allowing you to call the route as a function.

In your Scala code or Twirl template, it looks like this:

@link(controllers.html.routes.ProjectController.showProject(project.id)) {
    View Project Details
}

If you ever change the path in the routes file to /admin/projects/:projectId, the code above stays exactly the same, and the link updates automatically. I honestly can't stress this enough: if you find yourself typing a forward slash inside a string to build a URL in Play, stop and ask yourself why you aren't using the reverse router.

Handling Query Strings and Optional Parameters

Not everything fits neatly into a path. Sometimes you need query parameters for things like filtering or pagination. You define these in the routes file by adding the parameter without the colon prefix.

GET     /projects/search    controllers.ProjectController.search(query: String, page: Int ?= 1)

In this example, query is required, but page is optional with a default value of 1. The ?= syntax is a neat little trick that keeps your controller logic clean because you don't have to handle Option[Int] and manually call .getOrElse(1) every time you want to fetch a page of results.




📋 Practical Task

Implementing a Type-Safe Book Catalog Router

You are building a library management system. Your task is to configure the conf/routes file to handle the following requirements using type-safe routing:

  • A route to list all books: GET /books mapping to controllers.BookController.index.
  • A route to view a specific book by its ISBN (which is a String): GET /books/:isbn mapping to controllers.BookController.details(isbn: String).
  • A route to search for books by author with an optional "sort" parameter (String, defaulting to "asc"): GET /books/search mapping to controllers.BookController.search(author: String, sort: String ?= "asc").

Once you have defined these routes, write the Scala code snippet you would use in a Twirl template to create a link to the details page for a book with the ISBN "978-3-16-148410-0" using the reverse router.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.