Creating a REST API solution

In this post I’ll explore a solution for quickly creating a REST API. Yes, I know, “quickly” you say? It can be done! I done it! 🙂

I wanted to be able to retrieve and store user details in MySQL over a RESTful API; something I could abstract away from a front-end.

I spent a few days playing around with various micro-frameworks (Sinatra, Flask, Silex, etc.), but spent more time learning the syntax, quirks, installing gems and pip packages than actually building my interface.

Step 1 – set up Spark

Having been a Java developer for a few years in a previous role, I decided to have a play around to see if I could quickly knock up my REST API using pure Java. Not a task I thought I could do quickly, as I assumed I’d have to rely on heavyweight components such as Spring MVC and Hibernate.

How times have changed! I eventually came across Spark. Spark is a micro-framework based on Sinatra but written entirely in Java. I read the quickstart, fired up Eclipse, and added the spark-core dependency to my Maven pom.xml.

Step 2 – Creating a RESTful endpoint

I started off implementing a “GET a user by id” method. With Spark I was quickly able to create a RESTful endpoint and return some fake user details very quickly:

package net.morgz;
import static spark.Spark.get;
import spark.Request;
import spark.Response;
import spark.Route;
public class Main {
    public static void main(String[] args) {
        get(new Route("/users/:id") {
        public Object handle(Request request, Response response) {
            return  "User: username=test,";

Just running this class starts up the build in Jetty server:

== Spark has ignited ...
>> Listening on

I can then browse to http://localhost/users/1 and get the hard-coded user details back. Very simple.

Step 3 – Persisting data

Next, I needed a place to store my user data. I thought of using basic JDBC and creating some Data Access Object (DAO) classes but this, again, would take quite some time. I did some searching and came across a nice lightweight Java library that does all this for me. Ladies and Gentlemen, I give you OrmLite! … codeblock

OrmLite is extremely simple to use. Firstly, I added the ormlite-jdbc dependency to my Maven pom.xml.

I then created a ‘User’ model class to represent my users table. This contains three fields: the auto-incrementing id; a username; and e-mail address, all done with annotations:

package net.morgz.core.database;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "users")
public class User {
       @DatabaseField(generatedId = true)
    private int id;
    private String username;
    private String email;
       public User() {
        // ORMLite needs a no-arg constructor
       public int getId() {
       public String getUsername() {
            return this.username;
       public void setUsername(String username) {
        this.username = username;
       public String getEmail() {
        return email;
       public void setEmail(String email) { = email;

Step 4 – MySQL connection

I now needed a connection to a MySQL database. I installed the mysql-connector dependency using Maven and added a few more lines to my Main class to instantiate the MySQL driver and set up the connection details:

String databaseUrl = "jdbc:mysql://localhost/spark";
      ConnectionSource connectionSource = new JdbcConnectionSource(databaseUrl);

Now, to keep the code nice and clean, I’ve always used the Data Access Object pattern in Java. Much like the ‘Repository’ class in Doctrine for PHP, these classes adhere to the Single responsibility principle where the class should do one thing and one thing only. In this case, my DAO object should only perform operations on the user table. I was under the impression I’d have to create a DAO class from scratch but, OrmLite to the rescue again, it automatically created DAO objects for you:

Dao<User,String> userDao = DaoManager.createDao(connectionSource, User.class);

How awesome is that? 🙂

Step 5 – Creating the table

So, having a connection to the database and a DAO, I now needed to create my user table. For a quick win, I found that I could avoid migrations by using this neat little snippet:

TableUtils.createTableIfNotExists(connectionSource, User.class);

This line pretty much does what it says; it will create the users table if it doesn’t already exist.

Step 6 – RESTful POST request

Now I can go ahead and add some users via a RESTful POST request:

post(new Route("/users") {
    public Object handle(Request request, Response response) {
        String username = request.queryParams("username");
        String email = request.queryParams("email");
                       User user = new User();
                                  response.status(201); // 201 Created

With my Spark server running, if I fire a POST request to the following URL…


…I see the 201 ‘Created’ status returned and, on checking the database, the user has been persisted with ID 1. Pretty damn slick!

Step 7 – DAO class

I can now go ahead and change my “GET user by id” method to use the DAO class:

get(new Route("/users/:id") {
   public Object handle(Request request, Response response) {
       User user = userDao.queryForId(request.params(":id"));
       if (user != null) {
           return "Username: " + user.getUsername(); // or JSON? :-)
       } else {
           response.status(404); // 404 Not found
           return "User not found";

Step 8 – GET request

And if I now fire a GET request to:


I see the username returned! 🙂

At Box UK we have a strong team of bespoke software consultants with more than two decades of bespoke software development experience. If you’re interested in finding out more about how we can help you, contact us on +44 (0)20 7439 1900 or email