Enterprise Java

Javalin REST API

1. Introduction

This is an in-depth article related to the Javalin REST API. Javalin is a web framework used by Java and Kotlin developers. The framework runs on Jetty Web server. It is similar to koa.js.

2. Javalin

2.1 Prerequisites

Java 7 or 8 is required on the linux, windows or mac operating system. Maven 3.6.1 is required for building the javalin REST API .

2.2 Download

You can download Java 8 can be downloaded from the Oracle web site . Apache Maven 3.6.1 can be downloaded from Apache site.

2.3 Setup

You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:

Setup

JAVA_HOME="/desktop/jdk1.8.0_73"
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

The environment variables for maven are set as below:

Maven Environment

JAVA_HOME=”/jboss/jdk1.8.0_73″
export M2_HOME=/users/bhagvan.kommadi/Desktop/apache-maven-3.6.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH

2.4 Adding Dependencies

You need to add the below dependency in the pom.xml

Javalin Dependency

<dependency>
    <groupId>io.javalin</groupId>
    <artifactId>javalin</artifactId>
    <version>1.6.1</version>
</dependency>

2.5 Setting up Javalin 

You can create a JavalinExample class as shown below. In this example, Javalin web server is started at port number 7000. It is started with pointing to three routes : example.

Javalin Example

package org.javacodegeeks.javalin;

import org.javacodegeeks.javalin.Customer.CustomerController;
import io.javalin.Javalin;

public class JavalinExample {
    public static void main(String[] args) {
        Javalin example = Javalin.create()
                .port(7000)
                .start();

        example.get("/example", ctx -> ctx.html("Ths is a Javalin Example"));

    }
}

2.6 Create a Data Model

You can first create a Customer class which has properties id, name, and ssn. Sample code is shown below:

Javalin Data Model – Customer

package org.javacodegeeks.javalin.Customer;

public class Customer {
    public final int id;
    public final String name;
	public final int ssn;

    public Customer(int id, String name, int ssn) {
        this.id = id;
        this.name = name;
		this.ssn = ssn;
    }
}

2.7 Create a DAO

Now you can create a CustomerDAO class as shown below:

CustomerDAO

package org.javacodegeeks.javalin.Customer;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

class CustomerDao {

    private final List customers = Arrays.asList(
            new Customer(0, "George Smith",334872136),
            new Customer(1, "Tania Rogers",231872636),
            new Customer(2, "Carol Smith",431875136)
    );

    private static CustomerDao customerDao = null;

    private CustomerDao() {
    }

    static CustomerDao instance() {
        if (customerDao == null) {
            customerDao = new CustomerDao();
        }
        return customerDao;
    }

    Optional getCustomerById(int id) { return customers.stream().filter(customer -> customer.id == id).findFirst(); }

    Iterable getAllCustomerNames() {
        return customers.stream().map(customer -> customer.name).collect(Collectors.toList());
    }
}

2.8 Create a Model Controller 

You can now create a Customer Controller class as shown below:

CustomerController

package org.javacodegeeks.javalin.Customer;

import io.javalin.Handler;

import java.util.Objects;

public class CustomerController {
    public static Handler fetchAllCustomeNames = ctx -> {
        CustomerDao dao = CustomerDao.instance();
        Iterable allCustomers = dao.getAllCustomerNames();
        ctx.json(allCustomers);
    };

    public static Handler fetchById = ctx -> {
        int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id")));
        CustomerDao dao = CustomerDao.instance();
        Customer customer = dao.getCustomerById(id).get();
        if (customer == null) {
            ctx.html("Not Found");
        } else {
            ctx.json(customer);
        }
    };
}

Now you can compile the code using the command below:

Compile Command

mvn package

You can execute the code using the command below:

Execute Command

mvn exec:java -Dexec.mainCls=org.javacodegeeks.javalin.JavalinExample

2.9 Create a REST Endpoint

Now you need to add the new routes for customers, and customers/:id.

Example with New Routes

package org.javacodegeeks.javalin;

import org.javacodegeeks.javalin.Customer.CustomerController;
import io.javalin.Javalin;

public class JavalinExample {
    public static void main(String[] args) {
        Javalin example = Javalin.create()
                .port(7000)
                .start();

        example.get("/example", ctx -> ctx.html("Ths is a Javalin Example"));
        example.get("/customers", CustomerController.fetchAllCustomernames);
        example.get("/customers/:id", CustomerController.fetchById);
    }
}

You can access the Javalin RESTAPI routes example, customers, customers/:id using the following urls: http://localhost:7000/example, http://localhost:7000/customers,http://localhost:7000/customers/1. The output for the above urls is shown below:

Example Route Output

This is a Javalin Example

Customers Route Output

["George Smith","Tania Rogers","Carol Smith"]

Customers/:id Route Output

{"id":1,"name":"Tania Rogers","ssn":231872636}

3. Download the Source Code

Download
You can download the full source code of this example here: Javalin REST API

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button