3logy
3logy

Reputation: 2712

How to call another rest api from my controller in Micronaut like in Spring-Boot RestTemplate?

I have the following function from Spring Boot. I cannot do it with declarative client thus my uri domain changed after every call so i need a RestTemplate like in Spring Boot.

How can i achieve the same in Micronaut?

private static void getEmployees()
{
   final String uri = "http://localhost:8080/springrestexample/employees.xml";

   RestTemplate restTemplate = new RestTemplate();
   String result = restTemplate.getForObject(uri, String.class);

   System.out.println(result);
}

Upvotes: 1

Views: 4347

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27255

Something like this is a good starting point...

import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;

import javax.inject.Inject;

@Controller("/")
public class SomeController {
    // The url does not have to be
    // hardcoded here.  Could be
    // something like
    // @Client("${some.config.setting}")
    @Client("http://localhost:8080")
    @Inject
    RxHttpClient httpClient;

    @Get("/someuri")
    public HttpResponse someMethod() {
        String result = httpClient.toBlocking().retrieve("/springrestexample/employees.xml");
        System.out.println(result);

        // ...

        return HttpResponse.ok();
    }
}

I hope that helps.

EDIT

Another similar approach:

import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;

@Controller("/")
public class SomeController {
    private final RxHttpClient httpClient;

    public SomeController(@Client("http://localhost:8080") RxHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    @Get("/someuri")
    public HttpResponse someMethod() {
        String result = httpClient.toBlocking().retrieve("/springrestexample/employees.xml");
        System.out.println(result);

        // ...

        return HttpResponse.ok();
    }
}

Upvotes: 2

Related Questions