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.
Talk to one of our digital experts
Tom Houdmont
Head of Business Solutions
Do you have an idea or a project you need support with?
Tom leads Box UK’s Business Solutions team and has over 15 years experience in the web industry. Tom is passionate about creating impactful solutions that solve real problems and deliver the outcomes our clients need.
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(newRoute("/users/:id"){
@Override
public Object handle(Request request, Response response){
return"User: username=test, email=test@test.net";
}
});
}
}
Just running this class starts up the build in Jetty server:
== Spark has ignited ...
>> Listening on 0.0.0.0:4567
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;
@DatabaseField
private String username;
@DatabaseField
private String email;
public User(){
// ORMLite needs a no-arg constructor
}
public int getId(){
return this.id;
}
public String getUsername(){
return this.username;
}
public void setUsername(String username){
this.username = username;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.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:
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:
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:
…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(newRoute("/users/:id"){
@Override
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:
http://localhost:4567/users/1
I see the username returned! 🙂
Pete Withers-Jones
Head of Development
Pete Withers-Jones leads Box UK’s Development Practice, and has over 20 years of experience in software development, working across various industries and technologies.
Subscribe now and get our expert articles straight to your inbox!