openapiquarkusquarkus-rest-clientopenapi-generator-maven-plugin

Quarkus - how to use OpenAPI generated API as Quarkus rest client?


I have YAML definition from another project which will generate an ExternalAPI.java for me. I am using OpenAPI plugin of Maven.

Now, I also can do @RestClient in Quarkus, defining @RegisterRestClient(configKey="foo") and enable injection; also, @RegisterClientHeaders to inject some header.

Now, how to combine both? I want to keep using the annotations I mentioned, while making use of the generated API class.


Now, I am using RestClientBuilder:

RestClientBuilder.newBuilder()
        .baseUri(new URI(someUrl))
        .register((ClientRequestFilter) context -> context.getHeaders().put("MyToken", Collections.singletonList(token)))
        .build(ExternalAPI.class);

Usable, but little bit strange; I need to create the instance myself.


Solution

  • you can create an interface that extends the generated ExternalAPI interface and annotate it with @RegisterRestClient and @RegisterClientHeaders

    @RegisterRestClient(configKey="foo")
    @RegisterClientHeaders(MyHeadersFactory.class)
    public interface MyExternalAPI extends ExternalAPI {
    // define something
    }
    

    and now inject it in any service

    public class MyService {
        @Inject
        MyExternalAPI externalAPI;
    
        public void doSomething() {
            // use the externalAPI instance
        }
    }
    

    Now you can use the annotations you mentioned and make use of the generated API class. Quarkus will handle the instantiation of MyExternalAPI for you.