Helidon: Microservice REST API

0
53

Writing REST API with the Helidon framework is not a hard job since it is compliant with Microprofile specification. The good part is that we don’t need to learn any new technology or annotation to achieve this. In this example below I am going to explain how to write REST API by following Helidon MP.

The code is as follows,

//Country.java
public class Country {
    private String code;
    private String name;
    private String capital;

    public Country() {}

    public Country(String code, String name, String capital) {
        this.code = code;
        this.name = name;
        this.capital = capital;
    }

    public String getCode() {
        return code;
    }

    public String getName() {
        return name;
    }

    public String getCapital() {
        return capital;
    }
}
//CountryManager.java
@ApplicationScoped
public class CountryManager {
    public List<Country> all() {
        return CollectionsHelper
                .listOf(
                        new Country("IND", "India", "New Delhi"),
                        new Country("AUS", "Australia", "Canberra")
                );
    }
}
//ICountryApi.java
@Path("/countries")
@Produces(MediaType.APPLICATION_JSON)
@ApplicationScoped
public interface ICountryApi {
    @GET
    Response all();
}
//CountryApi.java
@ApplicationScoped
public class CountryApi implements ICountryApi {
    @Inject
    CountryManager manager;

    @Override
    public Response all() {
        System.out.println("Enters Country api");
        return Response
                .ok(manager.all())
                .build();
    }
}
//Finally add an entry into the application
@ApplicationScoped
@ApplicationPath("/")
public class DailyApiApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        return CollectionsHelper.setOf(
                CountryApi.class
        );
    }
}
Finally access the API using,
http://localhost:8080/countries

The code is so simple and straight forward. The entire code follows the annotation of JAX-RS specification which is part of our Microprofile specification. So the learning curve is nothing and no code is specific with Helidon. This is the beauty of Microprofile and the compliant frameworks. We can simply move this code to different Microprofile vendors based on our organization strategy changes. No code change is required to move between vendors.

{ Happy coding }