December 31, 2015

Ratpacked: Execute Handlers Based On Accept Header

A client of our Ratpack application can send a HTTP Accept header to indicate the type of response the client expects or can handle. We can restrict our application to certain types with the accepts method of the Handlers class. We can define one or more String values that denote the types that a client can use and our application responds to. If the value for the Accept header is one of the given values then the next handlers are invoked otherwise a client error 406 Not Acceptable is returned.

In the following example Ratpack application definition we use the accepts method so only values of application/json and application/xml:

// File: src/ratpack/ratpack.groovy
import static ratpack.handling.Handlers.accepts
import static ratpack.http.MediaType.APPLICATION_JSON
import static ratpack.groovy.Groovy.ratpack

ratpack {
    handlers {
        // If the Accept header contains application/json or
        // application/xml then continue with the rest of the
        // handlers.
        all(accepts(APPLICATION_JSON, 'application/xml'))

        get {
            render 'Developing with Ratpack is fun.'

Written with Ratpack 1.1.1.