Build Restful service with Java 8 in Five minutes

This is a very basic tutorial for beginners who would like to experiment with Java 8 and sparkjava.com Spark Framework.

Sometimes we can complex issues in our head more then it is, I was just trying to teach myself a way to make a simple Java Restful Api to handle few open and simple calls for me. I will share with you my start point.

We will use Intellij and create simple RestApi, basically if you have eclipse it is the same idea.


First lets create the project.
Open Intellij => Choose Maven project
Choose maven-archetype-quickstart
Click Next
intellij-maven

#You can choose whatever you wish in the groupid and artifactid
GroupId: my.simplejavarestapi.com
ArtifactId: simplejavarestapi
Click Next
intellij-maven-artifectid
#Continue

intellij-maven-setup

#You can choose your own project name
Project name: simplejavarestapi

intellij-maven-project

Finish

The project should open as the following:

start-pomxml

In the pom.xml we need to add dependecies, under depencies lets add:

We are done with our configuration, lets start with adding our code.

Spark uses an interface called ResponseTransformer to convert objects returned by routes to an actual HTTP response.this transfomer will route transforming output to JSON using Gson:

Create JsonTransformer.java

Lets create an pojo object that we will use in our code.
Create Greeting.java

In App.java lets add the lines.

Right click on App.java and click on Run ‘App.main()’
appmain

Open the browser and go to http://localhost:4567/greeting

GET: http://localhost:4567/greeting

 

POST: http://localhost:4567/greeting?name=Gabriel

 

PUT: http://localhost:4567/greeting?name=Gabriel

 

DELETE: http://localhost:4567/greeting?name=Gabriel

githubbutton

Download project from Github: https://github.com/gabriel-a/simplejavarestapi

Build Restful service with Java 8 in Five minutes