How to consume an API in a grails application
Asked Answered
S

2

9

I have a service running on this url: http://localhost:8888

I get results from this service by invoking it like this:

http://localhost:8888/colors?colorname=red&shade=dark

and I get the results back in JSON like this:

 {
      "request#": 55,
      "colorname": "red",
      "shade": "dark",
      "available": "No"
 }

Question

What are some ways by which I can consume this service in my grails application?

Statute answered 14/10, 2013 at 19:45 Comment(2)
Rest Client Builder plugin is sleek IMO.Frasco
Better answer can be found at #25471366Aught
F
14

Assuming all the configuration are there for rest client builder, you would end up with 2 lines of code consuming the service as:

//controller/service/POGO
def resp = rest.get("http://localhost:8888/colors?colorname=red&shade=dark")
resp.json //would give the response JSON

where

//resources.groovy
beans = {
    rest(grails.plugins.rest.client.RestBuilder)
}
Frasco answered 14/10, 2013 at 19:53 Comment(0)
G
0

I have experienced with RestBuilder brought in Grails 2.5.6 applications via rest-client-builder plugin. We don't need to declare a bean for RestBuilder class in resource.groovy.

Below is an example I used to demonstrate for my article.

JSONElement retrieveBioModelsAllCuratedModels() {
    final String BM_SEARCH_URL = "https://wwwdev.ebi.ac.uk/biomodels/search?domain=biomodels"
    String queryURL = """\
${BM_SEARCH_URL}&query=*:* AND curationstatus:\"Manually curated\" AND NOT isprivate:true&format=json"""
    RestBuilder rest = new RestBuilder(connectTimeout: 10000, readTimeout: 100000, proxy: null)
    def response = rest.get(queryURL) {
        accept("application/json")
        contentType("application/json;charset=UTF-8")
    }
    if (response.status == 200) {
        return response.json
    }
    return null
}
Gabriellia answered 12/4, 2020 at 17:19 Comment(2)
Hi Tung: well it could be correct not to use bean initialisation, but it is a best practice to initialise bean most used in order to avoid new instantiation each time you need, and RestBuilder is frequenlty used in an application so it is much better to make instantiation in resource (Spring best practice). I think if you want to teach to young grails programmers the correct way, it is using always resource for common bean init.Headway
I am thinking to declare a bean in resources depends on a case by case. Is this context, RestBuilder allows specifying some options for your remote connection such as connection timeout or proxy. I don't know how to do so if we use RestBuilder as dependency injection.Gabriellia

© 2022 - 2024 — McMap. All rights reserved.