RESTHeart Greetings Services Tutorial
This tutorial introduces two straightforward web services from the RESTHeart examples collection: textGreeter
and jsonGreeter
. These services generate greeting messages in different formats: textGreeter
delivers messages in text/plain
format, while jsonGreeter
uses application/json
.
This plugin serves as an example of how to create services in RESTHeart by implementing various specialized Service
interfaces, such as JsonService
and ByteArrayService
. It demonstrates handling requests and responses, retrieving query parameters, and setting the Content-Type
header.
Important
|
Explore Comprehensive RESTHeart Examples! If you’re looking to dive deeper into developing with RESTHeart, visit the RESTHeart examples to discover a rich collection of use cases and code samples. Highly recommended for an in-depth learning experience! |
What you need
To run this tutorial, the following are required:
1) Java 21: Install it using sdkman
$ sdk install java 21.0.3-tem
2) Docker: Necessary for running RESTHeart.
3) HTTPie: A command-line HTTP client for testing, available at httpie.io/cli
Note
|
The examples use Maven, but it’s accessible through the included Maven wrapper (mvnw ), so a separate installation is not required.
|
Building the Plugin
To build the plugin, run the following commands:
$ git clone --depth 1 git@github.com:SoftInstigate/restheart.git # clone restheart repo
$ cd examples/greeter-service # cd into the greeter-service example project root
$ ../mvnw clean package build the project
Running RESTHeart with the Plugin
This plugin doesn’t require MongoDB, so you can run RESTHeart in standalone mode using the -s
option.
Use Docker 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 more information, see RESTHeart with custom Plugin documentation.
Testing the Service
You can test the service with the following HTTP requests:
GET request, no query parameter
$ http -b :8080/textGreeter
Hello, World
GET request, with name query parameter
$ http -b :8080/textGreeter?name=Andrea
Hello, Andrea
POST request, with content body
$ http --raw 'Sara' :8080/textGreeter
Hello, Sara
Note: Using HTTP verbs other than OPTIONS
, GET
, or POST
for /textGreeter
will result in a HTTP 405 Method Not Allowed
response.
Plugin Code Description
Below is the code of the TextGreeterService
class that implements the Web Service /textGreeter
:
@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 ? "Anonymous" : name.getFirst()));
}
case POST -> {
var content = req.getContent();
res.setContent("Hello, " + (content == null ? "Anonymous" : new String(content)));
}
default -> res.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
}
}
}
The Java class TextGreeterService
is defined as a plugin for a RESTful service, as indicated by the @RegisterPlugin
annotation. This class is an implementation of the ByteArrayService
interface. 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 toHttpStatus.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.