Search code examples
springspring-bootapikotlinresttemplate

Best Pratices: How to modify RestTemplate so if (response is 401 and url is in a certain API list) then auto call login?


I am writing a Spring application using Kotlin that has:

  • API call is in 2 main list of API:
    • API belong to internal system: Automatic call login when response is 401 unauthorized
    • API being called by external service: Return response with error message when 401 unauthorized

Right now I'm using RestTemplate to call API, so my questions is what is the best pratices to modify RestTemplate so if (response is 401 and url is in the second API list) then auto call login?

Example of my code:

List API endpoints:

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration

@Configuration
class AppApiEnpoint(
        @Autowired
        private val appProperties: AppProperties
) {

    var orderCreateUrl: String = appProperties.getUrl("/order/create.json").toString()
}

API call

fun create(contentRequest: OrderSendAgentDto, accessToken: String): ResponseEntity<OrderResponseDto> {
    val requestUri = UrlBuilder(appApiEnpoint.orderCreateUrl).toString()

    val headers = HttpHeaders()
    headers.contentType = MediaType.APPLICATION_FORM_URLENCODED
    val body = HttpUtils.convertObject2Map(contentRequest)
    body.add("access_token", accessToken)
    val request = HttpEntity(body, headers)
    val restTemplate = RestTemplate()
    val response = restTemplate.postForEntity(requestUri, request, OrderResponseDto::class.java)

    return response
}

Note:

  • I did come up with a way to wrap the response in a Util method to handle this logic but if so then there will be a lot of code that was used before that I have to fix and new APIs are constantly being added during development. This is not an suitable approach

Solution

  • You can set ResponseErrorHandler to the rest template that should do auto-login, or even use @Retry with retry handlers on API methods that should do auto-login