Preferred way to make a web service call to complete a command

I think this is a simple question…I have a CommandHandler that needs to call an external REST API in order to complete the command. How is something like this generally done with Axon? Is this a QueryHandler that fetches data from REST over a data store? Or should I construct a client and inject it into the aggregate?

Thanks in advance for any advice!

I think you can do something like this

@StartSaga
@SagaEventHandler(associationProperty = "smsId")
fun handle(event: SendSmsRequested) {
    SagaLifecycle.associateWith("smsId", event.smsId.asReference())

    val response = webClient.post().uri(url).bodyValue(data).retrieve().bodyToMono(SmsResponse::class.java).block()
	
	if(response != "00000") 
		commandGateway.send<Status<Unit>>(RejectSendSms(event.smsId, smsResponse?.code, smsResponse?.message)).block()
	else
		commandGateway.send<Status<Unit>>(ConfirmSendSms(event.smsId, event.phoneNumber, event.message)).block()
	
    // You can use `queryGateway.subscriptionQuery` to get the emited object.
}


@EventHandler
fun on(event: ConfirmSendSms) {
    val rsp = mapping.map(event)
    saveDocument(rsp)
	
	queryUpdateEmitter.emit(GetSmsRs::class.java, { it.externalId == externalId }, rsp)
}
1 Like

Thank you for the response! I was actually going down this very path but wasn’t sure if this is the “right” way to do such a thing in Axon.

A Saga is a valid pattern, but it can also be a bit overengineered in specific scenarios.

Can you explain a bit more your use case?
does the call at this third-party client produce important information for your application? I’m asking this question because maybe you can configure your call to produce an event and store the needed data.

There are multiple ways to implement this, no silver bullet and nothing that is really specific to the framework per se.

Yes, this call provides important information to the use case for sure. I have a command to create an invoice, to get a total for the invoice I must reach out to a 3rd party to calculate taxes.

In this case scenario, a Saga is a good approach, indeed.