I want to send a simple POST request to another application to trigger some action there.
I have a quarkus project and want to send the request from inside my CreateEntryHandler – is this possible in a simple way? Or do I need to add something like Apache Httpclient to my project? Does it make sense in combination with quarkus?
Advertisement
Answer
The other application, I assume has an API Endpoint?
Lets state that the API endpoint you are trying to call in the other app is:
POST /v1/helloworld
From your Quarkus Application, you will have to do the following:
- Register a RestClient *As a Service
- Specify the Service information in your configuration properties
- Inject and use this Service
— In your current Application —
Pay close attention to the package name. IT has to match exactly in your application.properties file.
HelloWorldService.java
package com.helloworld.services
@Path("/v1")
@RegisterRestClient
public interface HelloWorldService{
@POST
@Path("/helloworld")
Response callHeloWorld(HelloWorldPojo payloadToSend);
}
//Notice that we are not including the /v1
in the mp-rest/url
, why? Because it is included in the @RestClient
path.
Update your application.properties to include the following:
com.helloworld.services.HelloWorldService/mp-rest/url=https://yourOtherApplication.com/API
— Your HelloWorldPojo which you will send as payload
HelloWorldProjo.java
@JsonPropertyOrder({"id", "name"})
public class HelloWorldProjo{
private long id;
private String name;
//Setters
//Getters
}
In another service where you actually want to use this:
ServiceWhichCallsYourOtherAPI.java
@RequestScoped
public class ServiceWhichCallsYourOtherAPI{
@Inject
@RestClient
HelloWorldService helloWorldService;
public void methodA(){
HelloWorldPojo payloadToSend = new HelloWorldPojo();
payloadToSend.setId(123);
payloadToSend.setName("whee");
helloWorldService.callHelloWorld(payloadToSend);
}
}
The POST request will then go to https://yourOtherApplication.com/API/v1/helloworld
The json will look like:
{
"id":123,
"name":"whee"
}
Really great read: https://quarkus.io/guides/rest-client