Chapter 3. Routing
This chapter covers
- Defining a route
- Choosing the right HTTP method
- Matching path expressions
- Exploring advanced routes
Scalatra is often referred to as a web framework. This is fair. Scalatra ably handles requests from a web browser and responds with dynamically generated HTML. But web framework fails to tell the whole story. We prefer to call Scalatra an HTTP framework. This distinction is subtle but important.
Scalatra often serves applications unrelated to web clients. It’s used for RESTful services that may serve a mobile application or integrate internal systems. One user even uses Scalatra to provide an interface to his home heater. This is all made possible by Scalatra’s firm embrace of HTTP.
Routes are the glue that binds HTTP requests to the blocks of Scala code that implement your application logic. New Scala developers with HTTP experience should find immediate comfort in Scalatra’s HTTP DSL. If you’re new to HTTP, don’t despair. Although full coverage of HTTP is out of scope for this book, we’ll cover enough to empower you to make the right decisions when designing your HTTP API. In this chapter, we’ll demonstrate routing with a simple music service.[1]
1We might not topple iTunes or Amazon Music, but we’ll have a good time name-checking our favorite artists.
Routes are declared directly in the body of your Scalatra application. Let’s look at an example in figure 3.1.