Contents

POST request to API with Kotlin and Spring RestClient (RestTemplate)

Contents

I am new in Kotlin. So maybe this post is just a bookmark for future. For example we want request some API for some data by POST to it an json array of ids from our Spring service.

First of all we need Jackson to parse API’s response. So check out your build.gradle file

1
implementation "com.fasterxml.jackson.module:jackson-module-kotlin"

And the example code for POST json request.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.web.client.RestTemplate

data class ApiEntity(val id: Int, val name: String, val status: String)


fun fetch(ids: MutableSet<Int>){
  val mapper = jacksonObjectMapper()
  val url = "http://api.yourserver.com/endpoint"
  val restClient = RestTemplate()
  val headers = HttpHeaders().apply {
      contentType = MediaType.APPLICATION_JSON_UTF8
  }

  val resp = restClient.postForEntity(url, HttpEntity(ids, headers), String::class.java)
  if (resp.statusCode.is2xxSuccessful) {
      // Parse string response into the List of ApiEntity 
      mapper.readValue<List<ApiEntity>>(resp.body!!).forEach {
          println(it)
      }
  } else {
      throw IllegalStateException()
  }

}