Creating an Ajax front-end to a Quarkus REST application

In this article we will check out how query a REST Service running with Quarkus with a minimal Ajax and jQuery client.

Quarkus applications can be quickly bootstrapped using the Maven or Gradle plugin available. The plugin will generate a minimal project structure with a sample REST Endpoint and the Quarkus’s Maven dependencies included in the configuration file. Let’s assume you are using Maven:

mvn io.quarkus:quarkus-maven-plugin:0.16.1:create     -DprojectGroupId=com.sample     -DprojectArtifactId=hello-quarkus     -DclassName="com.sample.DemoEndpoint"     -Dpath="/persons"

Within our DemoEndpoint class, let’s add methods to perform CRUD Operations:

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;


@Path("persons")
@ApplicationScoped
@Produces("application/json")
@Consumes("application/json")
public class DemoEndpoint {

    @Inject DemoRepository demoRepository;

    @GET
    public List<Person> getAll() {
        return demoRepository.findAll();
    }

    @POST
    public Response create(Person p) {
        demoRepository.createPerson(p);
        return Response.status(201).build();

    }

    @PUT
    public Response update(Person p) {
        demoRepository.updatePerson(p);
        return Response.status(204).build();
    }
    @DELETE
    public Response delete(@QueryParam("id") Integer id) {
        demoRepository.deletePerson(id);
        return Response.status(204).build();
    }

}

The Repository class uses a plain memory structure to store your objects:

package com.packt.quarkus.chapter4;

import javax.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;


@ApplicationScoped
public class DemoRepository {

    List<Person> list = new ArrayList();
    int counter;

    public int getNextCustomerId() {
        return counter++;
    }

    public List<Person> findAll() {
        return list;
    }

    public Person findPersonById(Integer id) {
        for (Person c: list) {
            if (c.getId().equals(id))  {
                return c;
            }
        }
        throw new RuntimeException("Person not found!");
    }

    public void updatePerson(Person person) {
        Person personToUpdate = findPersonById(person.getId());
        personToUpdate.setName(person.getName());
        personToUpdate.setSurname(person.getSurname());
    }

    public void createPerson(Person person) {
        person.setId(getNextCustomerId());
        findAll().add(person);
    }

    public void deletePerson(Integer id) {
        Person c = findPersonById(id);
        findAll().remove(c);
    }
}

Then, here is the POJO Class named Person:

public class Person {
    private Integer id;
    private String name;
    private String surname;

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", surname='" + surname + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }
}

Done with the server side. Now let’s add an index.hml page to display the List of Person in an HTML Table:

<html>
<head>
    <!-- little bit of css to beutify the table -->
    <link rel="stylesheet" type="text/css" href="stylesheet.css" media="screen" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>


    <script type="text/javascript">

$(document).ready(function () {
    $.getJSON("http://localhost:8080/persons",
    function (json) {
        var tr;
        for (var i = 0; i < json.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + json[i].id + "</td>");
            tr.append("<td>" + json[i].name + "</td>");
            tr.append("<td>" + json[i].surname + "</td>");
            $('table').append(tr);
        }
    });
});
</script>
</head>

<body>
<div align="left" style="margin-top: 10%;">
    <fieldset style="border: none;">
        <legend><strong>Users List</strong></legend>

        <!-- table to show data -->
        <table class="greyGridTable">
            <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Surname</th>
            </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </fieldset>
</div>

</body>
</html>

Some CSS style has been included in the file stylesheet.css:

table.greyGridTable {
  border: 2px solid #FFFFFF;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}
table.greyGridTable td, table.greyGridTable th {
  border: 1px solid #FFFFFF;
  padding: 3px 4px;
}
table.greyGridTable tbody td {
  font-size: 13px;
}
table.greyGridTable td:nth-child(even) {
  background: #EBEBEB;
}
table.greyGridTable thead {
  background: #FFFFFF;
  border-bottom: 4px solid #333333;
}
table.greyGridTable thead th {
  font-size: 15px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  border-left: 2px solid #333333;
}
table.greyGridTable thead th:first-child {
  border-left: none;
}

table.greyGridTable tfoot td {
  font-size: 14px;
}

That’s all. Make sure the following dependencies are included in your pom.xml file:

<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-resteasy</artifactId>
</dependency>

Run the application with

$ mvn compile quarkus:dev

Now we can try adding some data with cURL:

$ curl -d '{"name":"john", "surname":"black"}' -H "Content-Type: application/json" -X POST http://127.0.0.1:8080/persons
$ curl -d '{"name":"victor", "surname":"frankenstein"}' -H "Content-Type: application/json" -X POST http://127.0.0.1:8080/persons

Let’s surf to localhost:8080 to check that Data is listed in our table:

quarkus tutorial json ajax

Great. We could see how easily JSON data can be parsed with some help from jQuery and Ajax!

Found the article helpful? if so please follow us on Socials