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.


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.

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.

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;

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? :-)

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.

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! 

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";

And if I now fire a GET request to:


I see the username returned! :-)

About the author

Jon Morgan

Jon Morgan

Jon has been a software developer for almost 20 years. Working at Box UK he is focused on web and mobile technologies, combining this technical knowledge with an understanding of client requirements to deliver complex projects such as faceted search solutions, API integrations and data aggregation systems.


Owain Lewis

Mar 5th, 2014

Thanks Jon, Really enjoyed this and could see myself using it for similar use cases.

Misel Mesnjak

Oct 13th, 2014

Hi Jon, Great little article – just what I need for the upcoming small project. Could You please provide pom.xml file for this project if You used maven?


Oct 22nd, 2014

Great article!


Nov 21st, 2014

Maven dependency: com.sparkjava spark-core 2.0.0 After this article was written Spark has been updated to use Java 8 and lambdas, hello world example: public static void main(String[] args) { get(“/hello”, (req, res) -> “Hello World”); }

regina tam

Nov 29th, 2014

the main code doesen’t compile for e java8


Jan 30th, 2015

Hi, nice post. Can you please provide source code?

Jon Morgan

Jan 30th, 2015

Hi All, Glad you enjoyed this little blog post. I’ll get around to updating the application to use Java 8 and lambdas asap. I’ll also host the source on Github. Cheers, Jon.


May 18th, 2015

What is the Github link for this post? Thank you.

Johnathan Kanarek

Aug 10th, 2016

Cool, I will try to implement a simple REST server example, it will be much easier without Jersey.

Johnathan Kanarek

Aug 10th, 2016

However, I will follow these guidelines:

Add Your Comment

Related content

We're hiring. Let's talk. View available roles