Friday 8 November 2013

Exposing Grails URLMappings as JSON

I'm currently working in a REST API. The endpoints are increasing really fast and we haven't decided how to document it yet. Until that happens I was wondering it would be nice to know how to access URLMappings data at runtime.

We've created a controller where the URLMappings structure is exposed. Only thing we have to do is to access to "grailsApplication" and "grailsUrlMappingsHolder" beans.

import grails.converters.JSON

class RootController extends BaseApiController {
   
      def grailsApplication
      def grailsUrlMappingsHolder
  
      def listApiUrls() {
  
          def urlMappings = grailsUrlMappingsHolder.urlMappings.collect { [
  
                  name: it.mappingName?:'',
                  url: it.urlData.logicalUrls.first(),
                  methods: it.parameterValues,
                  parameters: it.constraints.propertyName
 
          ] }
  
  
          def root = [
  
              metadata: grailsApplication.metadata,
              urlMappings: urlMappings
  
          ]
  
          render root as JSON
  
      }
  
  }    

We put all the information in a map and convert it to JSON and....

{
  "metadata": {
    "app.version": "0.1",
    "app.grails.version": "2.2.4",
    "app.name": "yump-api"
  },
  "urlMappings": 
  [
    {
      "name": "",
      "url": "500",
      "methods": {
        "action": "handleValidationException",
        "controller": "exception"
      },
      "parameters": 
      [
      ]
    },
    {
      "name": "",
      "url": "500",
      "methods": {
        "action": "handleApiException",
        "controller": "exception"
      },
      "parameters": 
      [
      ]
    }...


Here we have a basic version of a API documentation with a few lines :)

2 comments:

  1. thank you, very good information - also visit our website http://solusisehatanda.com/

    ReplyDelete
  2. Thanks for sharing exact records. it is a first rate informative publish. your article is simply too properly.
    Keep posting those articles constantly
    for Extremely good article information please check the site
    oracle fusion training in Hyderabad

    ReplyDelete