Sunday, September 5, 2021

How to create RESTful Web Services using Restlet Framework in Java - Example Tutorial

Hello Java developer, if you are looking for an example of how to create RESTful web services using Restlet Framework in Java and Eclipse then you have come to the right place. Earlier, I have shared the best REST API Courses and in this tutorial, I will show you how to use Restlet for creating REST APIs in Java. The Restlet is one of the first open-source frameworks to create and deploy RESTful web services in Java. After the release of JAX-RS (Java API for RESTful Web Services) JSR - 317, Restlet also supports JAX-RS annotation and provides a consistent way to create both RESTful Server and Client. HelloWorld program is the traditional way to start with new technology and continuing to the tradition, we'll write our first Restlet program as HelloWorld. 

Since Restlet can be used to create on both client and server-side, we'll first expose a resource as a RESTful web service using the Restlet server and then consume the same RESTful web service by creating a RESTful client.

I'll use Maven and Eclipse to create this RESTlet HelloWorld example, if you are not familiar with Maven, it's a build automation tool like ANT for Java projects but also provides dependency management i.e. you don't need to download Restlet JAR manually, Maven will do it for you. To learn more about Maven see here.

And, if you are a complete beginner into RESTful web services then I also suggest you take a look at the Master Java Web Service and RESTful API with Spring Boot course by Ranga Rao on Udemy. It's a great hands-on course to learn how to develop RESTful web service in Java.

Tools Used

We have used the following tools, framework, and libraries to create and execute this Restlet example
  • Java
  • Eclipse Kepler
  • Apache Maven
  • Restlet framework

Now, let's see how the project looks like in Eclipse IDE.



Eclipse Project Structure

Here is how my Eclipse project structure looks like, we have three Java source files, RestletResource.java, RestletServer.java, and RestletClient.java

We are using an M2Eclipse plugin to use Maven inside Eclipse and this project is configured as a Maven project. 

In order to create the same setup on your machine, you need to first create a Maven Java project. You can also find some of my Maven Eclipse tips handy while using Maven with Eclipse for Java projects.

Restlet HelloWorld Example in Java and Eclipse



Maven Dependency

You need Restlet JAR files to run our Restlet HelloWorld Example. Each Restlet framework project least the restlet.jar which contains the Restlet core module and most of the use will also use Jackson for JSON support. If you are using Maven, you can just add the following dependency in your pom.xml and Maven will take care of downloading all JAR files.



One of the key thing to remember is configuring your Maven client to point to a dedicated Restlet repository as we did in the following snippet. This snippet is actually from the Restlet website and you can just add into your existing pom.xml. If you are using Maven project in Eclipse, just open the pom.xml and paste the following snippet there.
<repositories>
    <repository>
        <id>maven-restlet</id>
        <name>Restlet repository</name>
        <url>https://maven.restlet.com</url>
    </repository>
</repositories>
<properties>
    <restlet-version>2.3.7</restlet-version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.restlet.jse</groupId>
        <artifactId>org.restlet</artifactId>
        <version>${restlet-version}</version>
    </dependency>
    <dependency>
        <groupId>org.restlet.jse</groupId>
        <artifactId>org.restlet.ext.jackson</artifactId>
        <version>${restlet-version}</version>
    </dependency>
</dependencies>

You can see we just need restlet.jar, we are using 2.0.8 version. If you are not using Maven you can download following JAR from Maven central repository.

org.restlet-2.0.8.jar
org.osgi.core-4.0.0.jar


Steps to create HelloWorld in Restlet

Here are the steps you can follow to create this HelloWorld example using the Restlet framework:
  1. Create a Resource class by extending ServerResource class from the Restlet framework
  2. Create a Restlet Server by creating an instance of the Server class from the Restlet framework
  3. Connect to the URL Server is listening from a browser e.g. chrome
  4. Additionally, create a REST client to consume RESTful Web service exposed by our REST server

Now, let's understand the Java classes used in this example. Btw, if you are not very familiar with REST and Java then I suggest reading first the RESTful web service with JAX-RS because Restlet also implements JAX-RS API, which is the standard API for developing RESTful web services in Java.






RestletResource.java
REST is all about the resource, anything client is interested in is resource e.g. name of book, price, publisher, or even a book itself. RESTful Web service returns a representation of that resource. In Restlet, you can create a RESTful resource by extending ServerResource class. 

In this class, you can create methods which are called when the different HTTP method is used to access the server e.g. GET, POST or DELETE. How does Restlet know which method to call on which type of HTTP request? 

Well, we'll use annotation provided by the Restlet framework e.g. @Get to annotate a method that is supposed to be called when GET requests access to the resource, @Delete, @Post, etc. 

These annotations are defined in org.restlet.resource package.

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

public class RestletResource extends ServerResource {

  @Get
  public String hello() {
    return "HelloWorld in Restlet, this is GET method response";
  }

  @Delete
  public void bye() {
    System.out.println("Bye Bye, DELETE method called");
  }

}


RestletServer.java
This is our RESTful Server. The main() method in the above class creates an HTTP server connector, which is an instance of the Server class available in the org.restlet package. It’s configured with the protocol, the listening socket port, and the target Restlet that will handle the requests—in this case, the HelloServerResource class.

After launching this Java program, you can point your web browser to the http://localhost:8080 URL and get this line of text: "HelloWorld in Restlet, this is GET method response"

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

/*
 * A Restlet Server, it starts a server to listen on port 8080
 * and expose RestletResource as RESTful web service.
 * When you run this program, it will listen for HTTP traffic
 * on 8080, you can access this RESTful web service by connecting
 * your browser to 8080
 */
public class ResletServer {

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

Output
Jun 01, 2016 12:40:43 PM org.restlet.engine.http.connector.HttpServerHelper start
INFO: Starting the internal HTTP server on port 8080


RestletClient.java
Restlet not only is a server-side framework but also gives you the ability to write clients that consume and manipulate resources exposed on the web. On running the above client code in your IDE you will see “"HelloWorld in Restlet, this is GET method response" string on your console. 

That confirms that the client connected to Sever and retrieve the resource using the GET method. Even though this is a trivial example it teaches you a lot of basic stuff with Restlet. You can further expand your knowledge by reading Restlet in Action, one of the best books for developing RESTful Java web services using Restlet.

RESTful web services in java using Restlet framework


import org.restlet.resource.ClientResource;

/*
 * A Restlet client which can consume a RESTful web service.
 * This client consumes REST web service from http://localhost:8080/.
 * As oppose to browser, an RESTlet client provides more option to
 * test e.g. you can call any HTTP method e.g. GET, POST or DELETE
 */
public class RestletClient {

  public static void main(String[] args) throws Exception {

    ClientResource client = new ClientResource("http://localhost:8080/");
    client.get().write(System.out);
    // client.delete().write(System.out);;
  }

}

Output
Jun 01, 2016 1:27:30 PM org.restlet.engine.http.connector.HttpClientHelper
start
INFO: Starting the default HTTP client
HelloWorld in Restlet, this is GET method response


How to Run this Restlet Example

Since it's a client-server example, you need to first run the Server and keep it running. Once the Server has started successfully, then you can run the client. In our client, we have two ways to test, first by sending GET request and second by sending DELETE request. 

I have commented on the DELETE request but you can first run the GET request and then uncomment and run the DELETE request if you want to test that. Btw, if you are not sure about the purpose of different HTTP methods in the REST world, see here.

Here is how you can start our Restlet Server, just go to the RestletServer.java, right-click and choose the option "Run as Java application" as shown below:

How to run Restlet Server in Java



Here is how our Server logs will look like after starting:

How to create Restlet server in Java



and, here is how our Restlet client logs look like:

How to create Restlet client in Java


You can see from their logs that Server continue to run but the client program finished once the request ended.

That's all about the Restlet HelloWorld example in Java. In this example, you have learned how to create a Restlet server and a Restlet client which can send both GET and DELETE requests.  We have also learned how to expose an object as a REST resource using the Restlet framework.  

This program is good enough to start learning the Restlet framework but if you want to learn it for professional development, I strongly suggest joining these best Java REST Web service courses, it's a great collection with lots of examples, both simple and complex. A great resource for any serious Java developer who wants to use Restlet in production for exposing and accessing web services.


Other Spring and Web Services articles for Java EE developers
  • Difference between REST and SOAP Web Services? (answer)
  • Spring HelloWorld Example using Dependency Injection (tutorial)
  • How to create a JDBC connection pool using Spring? (tutorial)
  • 20 Hibernate Interview Questions for Java developers (article)
  • Difference between Idempotent and safe methods in HTTP? (answer)
  • Top 10 REST Web Service Interview Questions (answer)
  • How to convert JSON array to String array in Java? (tutorial)
  • How to parse large JSON responses using Jackson? (tutorial)
Thanks for reading this Java Restlet tutorial and example so far. If you find this tutorial useful please share it with your friends and colleagues. 

1 comment :

Elendar said...

Hello
You mention JSR-317 in the beginning, but this JSR is Java Persistence api 2.0, not JAX-RS (JSR 311 et 339)

Also, you don't use jax-rs annotation in your code, ie javax.ws.rs.GET, why ?

Post a Comment