2

i m not able to consume Google rest API in groovy.

I m newbie with groovy :S and i m using HTTPBuilder to ask the service. My code is:

 public static void testJSONPost() {
 def builder = new HTTPBuilder("https://www.googleapis.com/qpxExpress/v1/trips/search?key={$MY_WEB_KEY}")
     def result = builder.request(POST, JSON) { req ->
      uri.query = ["request": ["passengers": ["adultCount": 1],"slice": [["origin": "BOS","destination": "LAX","date": "2015-05-13"],["origin": "LAX","destination": "BOS","date": "2015-05-23"]]]]
             response.success = {resp, json ->
                     println "JSON POST Success: ${resp.statusLine}"

                     return json.name
             }

             response.failure = {resp ->
                     println "JSON POST Failed: ${resp.statusLine}"
             }
     }
}

testJSONPost()

I tried with curl example and it worked:

curl -d @reques.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY_WEB_KEY

The content of "reques.json" is:

 {
  "request": {
    "passengers": {
      "adultCount": 1
    },
    "slice": [
      {
        "origin": "BOS",
        "destination": "LAX",
        "date": "2015-05-13"
      },
      {
        "origin": "LAX",
        "destination": "BOS",
        "date": "2015-06-06"
      }
    ]
  }
}

The key that i m using is a web key.

Well i ll keep on searching and trying.

paulofer85
  • 555
  • 11
  • 15
  • What error do you get? Is MY_KEY the same as MY_WEB_KEY? what's the contents of reques.json? – tim_yates Apr 19 '15 at 18:50
  • @tim_yates thanks for your fast comment. I edited the question. The error is: 403 Forbidden I m new using httpBuilder i m trying to find error message but i m fighting with that... :S – paulofer85 Apr 19 '15 at 19:40
  • Your curl command doesn't seem to be doing a POST afaict. Wouldn't you need a -X POST? Also, in the groovy code, you seem to be adding the map to the url, not sending it in the body of the request? Not at a computer at the moment to verify though :-( – tim_yates Apr 19 '15 at 20:16
  • To add to the body in groovy, change your `uri.query = ...` line to start with `body = ...` – tim_yates Apr 19 '15 at 20:21
  • @tim_yates WOW you really make it! you were right just changing `uri.query = ...` to `body =...` made it work Thanks! – paulofer85 Apr 19 '15 at 23:22
  • Cool! :-D added as an answer – tim_yates Apr 20 '15 at 05:48

1 Answers1

1

In the groovy code, you seem to be adding the map to the url, not sending it in the body of the request?

To add to the body in groovy, change your

uri.query = ... 

line to start with

body = ... 
tim_yates
  • 167,322
  • 27
  • 342
  • 338