netbrain
netbrain

Reputation: 9304

Grails urlmappings, can one prefix urlmappings?

So for instance, say i have an API on a webapp, and i wish to use the same controllers and actions in the API as the rest of the webapp.

In my urlmappings file i have

"/api/$version/$apiKey/$controller/$acion/$id?"

and i also have a mapping like this:

"/blog/$year/$month/$day/$action" {
   controller = 'blog'
 }

Now the question is, can i somehow prefix the api urlmapping to the blog urlmapping so i can benefit from the $year, $month, $day variables? in such a way that a GET request to the following url would be valid:

GET /api/0.1/bs23mk4m2n4k/blog/2001/01/05/list

or am i forced to do the following request instead?

GET /api/0.1/bs23mk4m2n4k/blog/list?year=2004&month=01&day=05

Need help from an urlmappings GURU or a groovy runtime urlmappings maniuplation WIZARD :)

I want a solution that can reuse existing non-api urmappings, instead of having to redeclare them with the api path as a prefix.

Upvotes: 5

Views: 2292

Answers (3)

ataylor
ataylor

Reputation: 66059

You could have an ApiController strip off the api parameters, then redirect to the blog controller. For example:

"/api/$version/$apiKey/$rest**" {
     controller:'api'
     action:'default'
}


import org.codehaus.groovy.grails.web.util.WebUtils
class ApiController {
    def grailsUrlMappingsHolder

    def default = {
        // validate apiKey, etc
        WebUtils.forwardRequestForUrlMappingInfo(request, response, grailsUrlMappingsHolder.match("/${params.rest}"))
    }
}

The API controller has access to the version and apiKey params, and passes on the rest of the params to be processed by the blog controller's UrlMapping.

Upvotes: 3

mjspier
mjspier

Reputation: 6526

I think you want to use embedded variables. Check the url mapping reference: http://grails.org/doc/latest/guide/single.html#6.4 URL Mappings

just add the following mapping:

static mappings = {
   "/api/$version/$apiKey/$controller/$year/$month/$day/$action"()
} 

now you can use this url for example:

http://localhost:8080/api/0.1/bs23mk4m2n4k/blog/2001/01/05/list

now you get redirected to the list action in the blog controller. there you can use params to show the parameters from the url (as defined in the mapping).

ex.

params.version

Upvotes: 0

BadSkillz
BadSkillz

Reputation: 2003

I had somewhat the same problem, solved it using named url mapping: http://www.grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.4.9%20Named%20URL%20Mappings

Hope this helps!

in urlMapping:

name blogWithYear:"/api/$version/$apiKey/$controller/$year/$month/$day":{
controller = 'blog'
action = 'youraction'
}

<g:link mapping="blogWithYear" params="[$version:'0.1', ....., '$year: 2011']">
Show blog
</g:link>

With g:link you can now compile the url however you want, adding parameters.

Upvotes: -1

Related Questions