5

I have one REST API, which expects data. We are using following curl command for sending data and header information:

curl -X "POST" "https://xxx.xxx.xxx/xapplication/xwebhook/xxxx-xxxx" -d "Hello, This is data"

What will be the equivalent Groovy Script?

Anshul Patel
  • 845
  • 3
  • 8
  • 11

1 Answers1

6

Although for a simple GET you could use plain Groovy:

'https://xxx.xxx.xxx/xapplication/xwebhook/xxxx-xxxx'.toURL().text

However that doesn't give you much flexibility (different http verbs, content-type negociation...etc). Instead I would use HttpBuilder-NG which is a very complete library and it's built having Groovy syntax in mind.

Regarding a working JSON example, the following sends a JSON body in a POST request and parses back the response, which will be available as a traversable map:

@Grab('io.github.http-builder-ng:http-builder-ng-okhttp:0.14.2')
import static groovy.json.JsonOutput.toJson
import static groovyx.net.http.HttpBuilder.configure

def posts = configure {
    request.uri = 'https://jsonplaceholder.typicode.com'
    request.uri.path = '/posts' 
    request.contentType = 'application/json'
    request.body = toJson(title: 'food', body: 'bar', userId: 1)
}.post()

assert posts.title == 'foo'
Mario
  • 101
  • 4