How to Create a REST API With Helidon SE and Java?
Hello everyone, Today, we will show you how to create a simple REST API with Helidon SE 2.5.0 and Java 17.
Quick Overview:
- Helidon SE is designed to be a microframework that fortifies the reactive programming model. Helidon SE features three core APIs to engender a microservice -- a web server, configuration, and security -- for building microservices-predicated applications.
- Helidon's web server is an asynchronous and reactive API that runs on top of Netty. The WebServer interface includes support for configuration, routing, error handling, and building metrics and health endpoints.
- The Config loads and processes configuration properties(application.properties or application.yaml) in key/value format.
- The Security class provides support for authentication, sanction, and audit.
Let's begin,
Final Project Directory:
Maven [pom.xml]:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <parent> <groupId>io.helidon.applications</groupId> <artifactId>helidon-se</artifactId> <version>2.5.0</version> <relativePath>../../../applications/se/pom.xml </relativePath> </parent>
<groupId>com.knf.dev.demo</groupId> <artifactId>helidon-se-rest-hello-world</artifactId> <version>0.0.1-SNAPSHOT</version> <name>helidon-se-rest-hello-world</name> <description>Demo project for Helidon SE</description>
<properties> <version.java>17</version.java> <mainClass>com.knf.dev.demo. helidonseresthelloworld. HelidonSeRestHelloWorldApplication</mainClass> </properties> <dependencies> <dependency> <groupId>io.helidon.webserver</groupId> <artifactId>helidon-webserver</artifactId> </dependency> <dependency> <groupId>io.helidon.media</groupId> <artifactId>helidon-media-jsonp</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <source>${version.java}</source> <target>${version.java}</target> <release>${version.java}</release> <forceJavacCompilerUse>true </forceJavacCompilerUse> </configuration> </plugin> </plugins> </build></project>
HelloService.java
package com.knf.dev.demo.helidonseresthelloworld;
import java.util.Collections;import java.util.concurrent.atomic.AtomicReference;import javax.json.Json;import javax.json.JsonBuilderFactory;import io.helidon.config.Config;import io.helidon.webserver.Routing.Rules;import io.helidon.webserver.ServerRequest;import io.helidon.webserver.ServerResponse;import io.helidon.webserver.Service;
public class HelloService implements Service {
private static final JsonBuilderFactory JSON = Json. createBuilderFactory(Collections.emptyMap()); private final AtomicReference<String> greeting = new AtomicReference<>();
HelloService(Config config) { greeting.set(config.get("app.message"). asString().orElse("Empty")); }
@Override public void update(Rules rules) { rules.get("/", this::getDefaultMessageHandler); }
private void getDefaultMessageHandler (ServerRequest request, ServerResponse response) { sendResponse(response, "Knowledgefactory"); }
private void sendResponse (ServerResponse response, String name) { var message = String.format("%s %s!", greeting.get(), name); var returnObject = JSON. createObjectBuilder(). add("message", message).build(); response.send(returnObject); }}
application.properties:
server.port=9080app.message=Greetings from
Main
package com.knf.dev.demo.helidonseresthelloworld;
import java.util.logging.Logger;import io.helidon.common.reactive.Single;import io.helidon.config.Config;import io.helidon.media.jsonp.JsonpSupport;import io.helidon.webserver.Routing;import io.helidon.webserver.WebServer;
public class HelidonSeRestHelloWorldApplication {
private static final Logger LOGGER = Logger. getLogger(HelidonSeRestHelloWorldApplication. class.getName());
public static void main(final String[] args) { startServer(); }
private static Single<WebServer> startServer() {
// Load the default configuration using the // reate() method. var config = Config.create();
/* * Helidon's web server is an asynchronous and * reactive API that runs on top of * Netty. The WebServer interface includes * support for configuration, routing, * error handling, and building metrics * and health endpoints. */ var server = WebServer. builder(createRouting(config)). config(config.get("server")) .addMediaSupport(JsonpSupport.create()).build();
// Start web server var webserver = server.start();
webserver.thenAccept(ws -> { LOGGER.info("Web server started! http://localhost:" + ws.port() + "/hello"); ws.whenShutdown(). thenRun(() -> LOGGER.info("Web server is down!")); }).exceptionallyAccept(t -> { LOGGER.severe("Web startup failed: " + t.getMessage()); });
return webserver; }
private static Routing createRouting(Config config) {
var helloService = new HelloService(config);
return Routing.builder()
.register("/hello", helloService).build(); }}
Local Setup and Run the application
Step1: Download or clone the source code to a local machine. - Click here
Step2: mvn clean install
Step3: Run the Main java application
INFO: Web server started! http://localhost:9080/hello