Welcome to bytebang » The blog about all and nothing » Super simple REST API with Restlet

Super simple REST API with Restlet

Jun 06 2020

The Problem

In one of our projects we needed a small REST API for communication purposes.

In Java there are multiple ways how to achieve this. I did not want to set up an application server or something with a lot of dependencies - i just want it to work. So I searched for a simpler method to get it up and running ...

The Solution

I stumbled upon a framework named Restlet.The webpage describes exactly what it is and what it does:

The Restlet Framework helps Java developers build better web APIs that follow the REST architecture style. Adopted and supported by a large community of Java developers, Restlet Framework benefits from numerous resources available all over the Internet. Fully open source, it is freely downloadable and can be used under the terms of the Apache Software License.

Thanks to Restlet Framework’s powerful routing and filtering capabilities, unified client and server Java API, developers can build secure and scalable RESTful web APIs. It is available for all major platforms (Java SE/EE, Google AppEngine, OSGi, GWT, Android) and offers numerous extensions to fit the needs of all developers.

Bingo! The only thing that was missing was a simple example - here it is: It consists of two classes and the library org.restlet.2.4.0.jar.

import org.restlet.Server;
import org.restlet.data.Protocol;

public class MainProgram
{
public static void main(String[] args) throws Exception
{
     Server server = new Server(Protocol.HTTP, 8080, MyService.class);
     server.start();
}
}

The MainProgram class contains the main() method, where my second class is referenced as a parameter where the Webserver is instantiated.

import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class MyService extends ServerResource
{
@Get("json")
public String sayHello()
{
  String name = getQuery().getValues("name");
 return "{ \"greet\": \"" + name + "\" }";
}
}

The MyService class implements the method that should be called when the server recieves a GET request.

The final result is a simple working webserver without the need to install or configure anything.

gue@gue-laptop:~curl http://localhost:8080?name=bytebang | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    23  100    23    0     0  11500      0 --:--:-- --:--:-- --:--:-- 11500
{
 "greet": "bytebang"
}

This might not be the ideal setup for huge deployments, but for a quick implementation it works very well. If you need more, then you might have a look into my github repository, where I run a Grizzly based REST Webservice with more features.

Happy coding !


Get Social


(c) 2024, by bytebang e.U. - Impressum - Datenschutz / Nutzungsbedingungen
-