@HttpExchange is an annotation from Spring Framework. It can be used to create Http interface to easily request a Rest API from a java spring application.
This lib makes easier the use of http interface avoiding boilerplate code
for the moment, copy-paste the main code in your since it is not published on maven.
For example :
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.service.annotation.GetExchange;
import java.util.List;
public interface RegionContract {
//same as @HttpExchange(method = "GET", value = "/nomenclature/{id}")
@GetExchange("/nomenclature/{id}")
List<Region> getRegions(@PathVariable String id);
}
BEST PRACTICE ! Instead of writing the interface, generate it from an OpenAPI spec in a contract first approach
For example :
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.service.annotation.GetExchange;
import fr.insee.demo.httpexchange.autobeangeneration.HttpInterface;
import java.util.List;
@HttpInterface(baseUrl = "https://base.url.of.the.api.I.consume/")
public interface RegionContract {
//same as @HttpExchange(method = "GET", value = "/nomenclature/{id}")
@GetExchange("/nomenclature/{id}")
List<Region> getRegions(@PathVariable String id);
}
TIP You can also extend thie interface RegionContract to keep it pure from the framework
import fr.insee.demo.httpexchange.autobeangeneration.HttpInterface;
@HttpInterface(baseUrl = "https://base.url.of.the.api.I.consume/")
public interface RegionHttpInterface extends RegionContract{}
Just annotate a class scanned by spring with @EnableHttpInterface
:
import fr.insee.demo.httpexchange.autobeangeneration.EnableHttpInterface;
@EnableHttpInterface
// it can be a @Configuration class but it is not mandatory
class SimpleConfig{}
@Component
public record GreatService(RegionContract regionContract){
public List<Region> findRegionsById(RegionId regionId){
// call the remote API, get the result, map it to Region and return the result
return regionContract.getRegions(regionId.value());
}
}
- you can use placeholders with properties to define the base Url :
@HttpInterface(baseUrl = "${demo.baseUrl}")
- Just be aware to declare a
PropertySourcesPlaceholderConfigurer
bean
- Just be aware to declare a
- you can use an
errorHandlerBeanName
attribute in the annotation to declare a bean name which will be used as an error handler- Example at fr.insee.demo.httpexchange.SimpleExampleTest#withErrorHandler_ShouldHandle4xxResponseCode
- you must declare a bean with the name provided in
errorHandlerBeanName
attribute and whose type isResponseErrorHandler
- you can use attribute
basePackages
to specify which packages (including subpackages) will be scanned to find @HttpInterface annotated interfaces. IfbasePackages
is not specified, all classpath will be scanned.