days
1
2
hours
2
2
minutes
1
6
seconds
0
4
search
How to build JSON RESTful web services with Jooby

Meet Jooby – the new Micro Web Framework for Java 8

Edgar Espina
Freeze light – infinity image via Shutterstock

A little while ago we introduced Jooby – a micro web framework for Java 8 inspired by express.js. In this article, Jooby creator Edgar Espina explains how to build a simple JSON RESTFUL web service with the framework.

We will write some routes using the script programming model.
The service will be available at:

http://localhost:8080/greeting

and produces a JSON response:

{
  "id": 1,
  "name": "Hello World!"
}

Requirements

Make sure you have all these software installed it in your computer:

Ready

Open a terminal (console for Windows users) and paste:

mvn archetype:generate -B -DgroupId=hellorestful -DartifactId=hello-restful -Dversion=1.0 -DarchetypeArtifactId=jooby-archetype -DarchetypeGroupId=org.jooby -DarchetypeVersion=0.13.0

An almost empty application is ready to run, you can try now with:

cd hello-restful

mvn jooby:run

Open a browser and type:

http://localhost:8080

TIP: If you are using an IDE that automatically compiles your source code while you save it… mvn jooby:run will detects those changes and restart the application for you!! more at mvn jooby:run.

Quick preview

Before moving forward let’s have a look at src/main/java/hellorestful/App.java:

public class App extends Jooby { // 1 extends Jooby

  {
    // 2 define some routes
    get("/", () -> "Hello World!");
  }

  public static void main(final String[] args) throws Exception {
    // 3 start the app
    new App().start(args);
  }

}

Do you see the comments in the source code?

  1. A Jooby app always extends org.jooby.Jooby
  2. We define some routes in the instance initializer (this is NOT static code).
  3. A Jooby app need to be instantiated and then started.

Getting dirty

Now we already see how a Jooby app looks like, we are going to create a simple greeting RESTFUL web service at http://localhost:8080/greeting

The Greeting.java:

public class Greeting {

  public int id;

  public String name;

  public Greeting(final int id, final String name) {
    this.id = id;
    this.name = name;
  }

  public String toString() {
    return name;
  }
}

And the new route:

import java.util.concurrent.atomic.AtomicInteger;
...

{
  AtomicInteger idgen = new AtomicInteger();

  get("/greeting", () -> new Greeting(idgen.incrementAndGet(), "Hello World!"));
}

Open a browser and type:

http://localhost:8080/greeting

You’ll see Hello World! in your browser, not bad ugh?

Not bad at all! But, don’t we suppose to build a JSON RESTFUL web service?

Absolutely, but before that, let’s see how to add a simple and optional HTTP parameter.

Adding a name parameter

We are going to improve our service by allowing a name parameter:

...
{
  ...
  get("/greeting", req -> {
    String name = "Hello " + req.param("name").value() + "!";

    return new Greeting(idgen.incrementAndGet(), name);
  });
}

HTTP parameter are accessible via req.param(String) method, that is why we change a bit our route to access the HTTP request.

Try it:

http://localhost:8080/greeting?name=Jooby

What if you call the service without a name? You will get a Bad Request(400) response. Let’s fix that with an Optional parameter:

...
{
  ...
  get("/greeting", req -> {
    String name = "Hello " + req.param("name").value("World") + "!";

    return new Greeting(idgen.incrementAndGet(), name);
  });
}

Same as before, we ask for the HTTP parameter but this time we set a default value: World. Optional parameters can be retrieve with:

Optional name = req.param("name").toOptional();

or from helper methods, like: .value(String).

Try it again with or without a name parameter!!

path parameter

If you want or prefer a path parameter, you can replace the path pattern with: /greeting/:name or allow both of them:

...
{
  ...
  get("/greeting", "/greeting/:name", req -> {
    String name = "Hello " + req.param("name").value("World") + "!";

    return new Greeting(idgen.incrementAndGet(), name);
  });
}

Try it:

http://localhost:8080/greeting?name=Jooby

Or:

http://localhost:8080/greeting/Jooby

Nice, ugh?

JSON

As you already known, Jooby is a micro-web framework in order to write a JSON response we need one of the available json modules.

Here we will use jackson but keep in mind the process is exactly the same if you choose any other module.

First of add the jackson dependency to your pom.xml:

<dependency>
  <groupId>org.jooby</groupId>
  <artifactId>jooby-jackson</artifactId>
</dependency>

If mvn jooby:run is running, please restart it (we need to force a restart bc we added a new dependency).

Let’s use the module in our App.java:

import org.jooby.json.Jackson;
...

{
  use(new Jackson());

  ...

  get("/greeting", "/greeting/:name", req -> {
    String name = "Hello " + req.param("name").value("World") + "!";

    return new Greeting(idgen.incrementAndGet(), name);
  });
}

Our service method didn’t change at all! We just import the jackson module using use(Module) method!!

Now, try the service again and you will get a nice JSON response:

{
  "id": 1,
  "name": "Hello World!"
}
Author

Edgar Espina

Open Source enthusiast. Creator of http://jooby.org, handlebars.java and others.


Leave a Reply

Be the First to Comment!

avatar
400
  Subscribe  
Notify of