Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
ratpack respond by content

Ratpack handler with byContent response

Ratpack is a Java/Groovy framework for rapid development of microservices.

Define set of handlers in src/main/Ratpack.groovy. Define common prefix api for REST APIs.

import static ratpack.groovy.Groovy.groovyTemplate
import static ratpack.groovy.Groovy.ratpack
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import groovy.json.JsonBuilder
import groovy.xml.MarkupBuilder

ratpack {
  handlers {
    prefix("api") {
      handler {
        // common code for all api calls
        // log all HTTP request headers
        request.headers?.names?.each { name ->
          logger.debug("HEADER: ${name}, VALUES: ${request.headers?.getAll(name)}")
        // call next handlers
      get {
        // IMPORTANT: if HTTP header 'Accept' is not given then first declaration from inside byContent takes place.
        byContent {
          json {
            def builder = new JsonBuilder()
            builder.root {
              type: "JSON"
            render builder.toString()
          xml {
            def sw = new StringWriter()
            builder = new MarkupBuilder(sw)
            builder.root {
              type(a: "A", b: "B", "XML")
            render sw.toString()

Run project from inside project's folder

$ ./gradlew run

Test what is returned by different conent type:

  • JSON

      $ curl -X GET -H "Accept: application/json" http://localhost:5050/api
  • XML

      $ curl -X GET -H "Accept: application/xml" http://localhost:5050/api
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.