RESTHeart Framework Tutorial: How Easy It Is to Implement a Web Service Today!
In this tutorial, we’ll dive into the simplicity and power of RESTHeart by walking you through the creation of a basic web service; with just a few tools and steps, you’ll see how easy it is to get a web service up and running today!
Whether you’re new to RESTHeart or looking to expand your knowledge, this guide will provide a clear and practical introduction to building RESTful services using the ByteArrayService interface.
RESTHeart’s examples collection features a basic yet functional web service: textGreeter
that provides greeting messages in text/plain
format.
This service exemplifies the implementation of ByteArrayService
interface within RESTHeart, focusing on request and response handling, query parameter retrieval, and setting the Content-Type
header.
For an in-depth understanding of RESTHeart’s capabilities, users are encouraged to explore the RESTHeart examples, a comprehensive resource offering a variety of use cases and code samples.
Setup
The tutorial necessitates the following setup:
- Java 21: Install using sdkman:
$ sdk install java 21.0.4-tem
- Docker: Required to run RESTHeart.
- HTTPie: A command-line HTTP client, available at httpie.io/cli. Maven is used in the examples, but a separate installation is not needed due to the inclusion of a Maven wrapper (
mvnw
).
Building the Plugin
To build the plugin, execute the following commands:
$ git clone --depth 1 git@github.com:SoftInstigate/restheart.git # clone restheart repo
$ cd examples/greeter-service # navigate to the greeter-service example project root
$ ../mvnw clean package # build the project
Running RESTHeart with the Plugin
This plugin does not require MongoDB and can be run in standalone mode with RESTHeart using the -s
option.
The following Docker command is used to start RESTHeart with the plugin:
$ docker run --rm -p 8080:8080 -e RHO="/fileRealmAuthenticator/users[userid='admin']/password->'secret';/http-listener/host->'0.0.0.0'" -v ./target:/opt/restheart/plugins/custom softinstigate/restheart:latest -s
For detailed information, refer to the RESTHeart with custom Plugin documentation.
Testing the Service
GET request without a query parameter:
$ http -b :8080/textGreeter
Hello, World
GET request with a name query parameter:
$ http -b :8080/textGreeter?name=Sara
Hello, Sara
Note: Other HTTP verbs for /textGreeter
result in a HTTP 405 Method Not Allowed
response.
Service Code Description
The TextGreeterService
class, implementing the /textGreeter
Web Service, is structured as follows:
package org.restheart.examples;
import org.restheart.exchange.ByteArrayRequest;
import org.restheart.exchange.ByteArrayResponse;
import org.restheart.plugins.ByteArrayService;
import org.restheart.plugins.RegisterPlugin;
import org.restheart.utils.HttpStatus;
@RegisterPlugin(name = "textGreeter", description = "just another text/plain Hello World")
public class TextGreeterService implements ByteArrayService {
@Override
public void handle(ByteArrayRequest req, ByteArrayResponse res) {
res.setContentType("text/plain; charset=utf-8");
switch (req.getMethod()) {
case OPTIONS -> handleOptions(req);
case GET -> {
var name = req.getQueryParameters().get("name");
res.setContent("Hello, " + (name == null ? "World" : name.getFirst()));
}
case POST -> {
var content = req.getContent();
res.setContent("Hello, " + (content == null ? "World" : new String(content)));
}
default -> res.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
}
}
}
This Java class is designated as a plugin for a RESTful service via the @RegisterPlugin
annotation. As an implementation of the ByteArrayService
interface, it includes methods to handle various HTTP methods, setting content types, and generating appropriate responses based on request content or parameters.
Let’s break down its structure and functionality:
Annotation — @RegisterPlugin:
- This annotation is used to register the class as a RESTHeart plugin.
- It has two parameters:
name
: the identifier for this service. The endpoint defaults to/textGreeter
since it is not explicitly defined by the annotation parameterdefaultURI
.description
: provides a brief description of what this service does.
Class Declaration:
public class TextGreeterService implements ByteArrayService
: this indicates thatTextGreeterService
is a public class implementing theByteArrayService
interface.
Method — handle(ByteArrayRequest req, ByteArrayResponse res):
- This method is an override from the
ByteArrayService
interface. - It takes two parameters: a
ByteArrayRequest
(namedreq
) and aByteArrayResponse
(namedres
).
Setting the Content-Type:
res.setContentType("text/plain; charset=utf-8")
:- This line sets the content type of the response to
text/plain
withUTF-8
charset, indicating that the response will be plain text.
Handling Different HTTP Methods:
The service uses a switch statement to handle different HTTP request methods.
For each case, there’s a different way to handle the request:
OPTIONS
: Calls a methodhandleOptions(req)
, an inherited convenient method that handles it for you providing CORS support.GET
: Retrieves a query parametername
from the request. Ifname
is not provided, it defaults toWorld
. The response content is set to "Hello, [name]". *POST
: Gets the content of the request. If no content is provided, it defaults toWorld
. The response is similar to the GET method, greeting the content of the request.- For any other HTTP method, the service sets the response status code to
HttpStatus.SC_METHOD_NOT_ALLOWED
, indicating that the method is not supported.
In summary, TextGreeterService
is a RESTHeart service plugin designed to respond with a simple text greeting. It handles GET and POST requests differently based on the input it receives (either through query parameters or request body) and defaults to greeting "World" if no specific input is provided. It also handles OPTIONS requests and rejects unsupported methods.
In conclusion, the RESTHeart Greetings Services Tutorial showcases the straightforward and efficient process of building web services with RESTHeart.