Skip to main content
1138

Create a Data API with Ballerina and H2

Created
Active
Last edited
Viewed 247 times
4 min read
3

This is a short tutorial on how you can quickly create a REST API to perform some basic database queries on an H2 database using Ballerina. I used Ballerina 2201.1.1 (Swan Lake Update 1). If you haven't downloaded and installed Ballerina yet, follow the instructions here.

1. Create a Ballerina package

Create a new Ballerina package by executing the following command in the terminal inside a directory you want to create the package:

bal new h2_data_api

Go to the created package and open VS Code:

cd h2_data_api

code .

The folder structure of the package should look like this:

enter image description here

2. Create the H2 database and table

An open source, SQL Database and written in Java, H2 is widely used as an in-memory database, or if you wish to persist your data in the H2 database, you should store the data in a file. We’ll be doing the latter in this tutorial.

2.1 Add the H2 driver

The H2 driver is required to connect to and interact with a H2 database. In this example, we’ll be adding the H2 database driver as a dependency in the Ballerina.toml file (this sample is written using H2 2.0.206 and it is recommended to use an H2 JAR with a version higher than 2.0.2).

To add the dependency, add the the following Maven dependency parameters for the H2 driver to the Ballerina.toml file.

[[platform.java11.dependency]]

artifactId = "h2"

version = "2.0.206"

groupId = "com.h2database"

enter image description here

2.2 Execute SQL queries to create the database and table

We'll be creating a database with a single table, which holds information about some of the most popular TV show characters. Let’s go ahead and use the main function in the main.bal file to create the database and table, and to populate the table with some data. Replace your main.bal file with the following code:

import ballerinax/java.jdbc;
import ballerina/io;
 
public function main() returns error? {
   io:println("Start of main function.. ");
 
   jdbc:Client jdbcClient = check new ("jdbc:h2:file:./target/tv_characters",
"rootUser", "rootPassword");
 
   // Creates a table in the database.
   _ = check jdbcClient->execute(`CREATE TABLE TV_Characters(id INTEGER
           NOT NULL GENERATED BY DEFAULT AS IDENTITY, firstName  VARCHAR(300),
           lastName  VARCHAR(300), tvShow  VARCHAR(300), voteCount INTEGER,
           PRIMARY KEY (id))`);
 
   // Add records to the newly-created table.
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Michael','Scott', 'The Office', 6234)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Arya','Stark','Game of Thrones', 100)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('David','Rose',${"Schitt's Creek"}, 200)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Beth','Harmon', ${"The Queen's Gambit"}, 9000)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Sherlock','Holmes','Sherlock', 350)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Walter','White', 'Breaking Bad', 10000)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Tyrion','Lannister', 'Game Of Thrones', 8000)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Jesse','Pinkman','Breaking Bad', 435)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Ross','Geller', 'Friends', 524)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Trevor','Bingley', 'Man vs Bee', 110000)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Chandler','Bing', 'Friends', 7208)`);
   _ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Tony','Soprano', 'The Sopranos', 7435)`);
 
   check jdbcClient.close();
 
   io:println("End of main function.. ");
 
}

Run the program to create the database and tables:

bal run

Quick Notes:

The snippet below creates a new H2 database named tv_characters in the target folder when you run the program.

   jdbc:Client jdbcClient = check new ("jdbc:h2:file:./target/tv_characters",
"rootUser", "rootPassword");

This statement below and the subsequent lines execute insert operations on the TV_Characters table. The TV_Characters table consists of the columns firstName, lastName, tvShow, and voteCount.

_ = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,lastName, tvShow, voteCount) VALUES ('Michael','Scott', 'The Office', 6234)`);

In case you're wondering what the _ is, the value of the underscore variable, a predefined variable of type any, is an ignored value.

Now that the table is populated with some data, let’s look at exposing and modifying this dataset via an API.

3. Create the API to perform DB queries

Let’s create the API now. We'll be creating the API file in the same package, so go ahead and create a new file named tv_characters_api.bal.

Copy the following code to the tv_characters_api.bal file.

import ballerinax/java.jdbc;
import ballerina/sql;
import ballerina/io;
import ballerina/http;
 
// Defines a record to load the query result schema
type TVCharacter record {
   int id;
   string firstName;
   string lastName;
   string tvShow;
   int voteCount;
};
 
final jdbc:Client jdbcClient;
 
function init() returns error? {
// Initializes the JDBC client.
   jdbcClient = check new ("jdbc:h2:file:./target/tv_characters",
       "rootUser", "rootPassword");
   io:println("Service initialized.. ");   
}
 
service /tv_characters on new http:Listener(9090) {
 
   isolated resource function get top10() returns TVCharacter[]|error {
       TVCharacter[] characters = [];
       stream<TVCharacter, error?> resultStream =
           jdbcClient->query(`SELECT * FROM TV_Characters ORDER BY voteCount DESC LIMIT 10;`);
 
       check from TVCharacter character in resultStream
           do {
               characters.push(character);
           };
       check resultStream.close();
       return characters;
 
   }
 
   isolated resource function post character(@http:Payload TVCharacter character) returns int|error? {
 
       sql:ExecutionResult result = check jdbcClient->execute(`INSERT INTO TV_Characters (firstName,
           lastName, tvShow, voteCount) VALUES (${character.firstName},${character.lastName},${character.tvShow}, 1)`);
 
       int|string? lastInsertId = result.lastInsertId;
       if lastInsertId is int {
           return lastInsertId;
       } else {
           return error("Unable to obtain last insert ID");
       }
   }
 
}

Quick Notes:

A single entry from the query result will be mapped to the TV_Character record.

The init function of the service (our API) will establish the connection to the tv_characters database we created earlier.

The tv_characters service is associated with an http:Listener, the Ballerina abstraction that deals with network-level details such as the host, port, SSL, etc.

The service contains two resource functions:

  • The get top10 function serves HTTP GET requests to the endpoint /tv_characters/top10 and returns the top 10 most popular TV show characters based on the vote count in the database via a SQL SELECT query.

  • The post character function serves HTTP POST requests to the endpoint /tv_character/character to insert a new TV show character to the table via an SQL INSERT.

4. Run the API

Note that you will have to delete the target folder if you ran the main function previously as the H2 database and tables are already created there. Or else, you can run the service in a separate package, and change the path to the DB correctly.

Run the service as follows:

bal run

5. Try out the API

Run the following cURL command to see the top 10 most popular TV show personalities:

curl http://localhost:9090/tv_characters/top10

Edit as needed and run this command below to add your favourite character to this database:

curl -X POST -H "Content-Type: application/json" \
  -d'{
 "id": 0,
 "firstName": "Jim",
 "lastName": "Halpert",
 "tvShow": "The Office",
 "voteCount": 4500
 }' \http://localhost:9090/tv_characters/character/  

And that’s a wrap! All code and configuration files can be found here.

Do also check out this article on how to create a data service using Ballerina and MySQL and the documentation for the ballerinax/java.jdbc package.