Building a Java REST API
Tags: Software Engineering, Java, Programming, Rest Api, Web Development

Rest (REpresentational State Transfer) API (Application Program Interface) a lot of abbrevations, but what is a REST API and how is it related to Web Applications?

It’s very unlikely that you have never met or interacted with a REST API before, when using different web applications/services. Take forexample Google Maps, when you enter a location and the Map service provide you with driving guidelines presented nicely within the Google Maps GUI(Graphical User Interface). Such task is completed using API’s communicating with the Google Servers requesting the needed data. In that way you do never directly talk to the servers containing the actual information.

Lets start with REST, what is it? REST is an architectual style, which in most cases is based on HTTP protocols to communicate between different services/clients. It’s in it’s simple sense a set of constraints and properties used to define such communication. When HTTP is used the following operations are avalible:

GET — Request data from a specified resource (Get relevant posts on your Facebook Wall)

— Request data from a specified resource (Get relevant posts on your Facebook Wall) POST — Submits data to be processed (e.g save a user in a Database)

— Submits data to be processed (e.g save a user in a Database) PUT — For saving or updating a resource on the server

— For saving or updating a resource on the server DELETE — For deleting a given resource

With the basic understanding of how API’s are used and what operations are available over HTTP, it’s time to look into how such can be implemented. Within large web applications we will often need several API’s in order to process and offer different services like e.g creating users, saving posts and editing of profile information. When web API’s are combined we often refere to them as a Mashup.

A Mashup in web development is a web application that uses content from more than one source to create a single new service displayed in a single graphical interface. 1.

It’s therefore important to be aware of how we deploy different API’s based on how they are to be used. To do so, we refere to release polices. The following release polices are normaly used:

Private : The API is for internal company use only

: The API is for internal company use only Partner: Only specific business partners can use the API

Only specific business partners can use the API Public: The API is available for use by the public

With this short introduction to the different aspects of REST API’s it’s time to show how such can be developed and deployed. For this we will create a Public available API, in the programming language Java, running on a localhost environment.

For the implementation Spring Boot will be used, which is a popular Java framework for building web and enterprise applications. For more info about Spring Boot Click Here. To start up our REST API project navigate to http://start.spring.io, here the packages and version for our project will be set. To ensure you have the right setup you settings should look similar to the following picture.

Once your setup is similar to the picture above, click Generate Project. The Group/Artifact can however be named as you wish, to match your project. The next step is to open the project within an IDE. When opened for the first time, the IDE will most likely load for a few secs/min in order to setup dependencies. To ensure that you setup is right and that your application is able to compile and execute, run the project as a Java application within your IDE. If the build succeeded you will see something similar to this in the console:

Tomcat started on port(s): 8080 (http) with context path ‘’

Started RestApiDemoApplication in 3.332 seconds (JVM running for 5.3)

With that being tested it’s time to get into the code. Navigate to src/main/java/yourPackageName/yourAtifactNameApplication.java. Here we will create our first Controller, which is a normal .java file with certain specifications within the code. As an example we will create a GET method which returns a String. We will do the following steps.

Create a java class, e.g HelloWorldController.Java Define your class as a Controller in order to specify that our class needs to handle REST Requests using @Controller Create a method which returns a string e.g helloWorld Define the request type by using @RequestMapping and the path in which we will access it over HTTP e.g “/Hello”.

Once complete your file should look like this.

Once completed, restart your application and you should now be able to navigate to localhost:8080/hello and see the following.

We have now created our first REST API with a GET method.

In order to secure a REST API or anything else for that matter, we need to have a formal understanding of what security is within this context. This tutorial will focus on security centered around Authentication and Authorization as this is what we are going to center our implementation around.

Authentication

Authentication is the act of proving the identity of who we are. So when someone is trying to access our REST API, we want to ensure that the caller can be identified and thereby only allow trusted users to access the service. The most basic way of authentication is by using a User/password approach which works if we trust that the password is kept secure. However there are other ways of Authentication and these can be combined in what is called Two Factor Authentication. Two Factor Authentication is acomblished by using two or more techniques to authenticate. See example of such techniques below:

Something you know (e.g A user account containing a username and Password)

Something you have (e.g A mobile phone where a SMS can be send with a unique code)

Somerthing you are (Biometics e.g fingerprint or eye scanner)

Authorization

Authorization is the step following that a given user has Authenticated successfully. Authorization is the process of giving someone permission to do or access something. So if we have a Web Application there might be a set of Services which regular users can access and a set of admin services that only a admin is supposed to use. The users in the system is thereby divided into groups which will be given different authorization rights even though both groups can authenticate to the same Web Application.

Securing our REST API

Now that the differences between Authentication and Authorization has been established it’s time to look further into how we can achieve such for our Java REST API using Basic Authentication. In this guide we will make use of the Spring Security Framework which is the de-facto standard for securing Spring-based applications. For more about Spring Security, see: https://spring.io/projects/spring-security. If you have followed the steps in Part 1 of this tutorial you can implement this without much effort. All you need to do to add this Framework to your project is to add the following to your POM.xml file. within the dependencies tag.

In this part of the tutorial we will stick to basic Authentication with the use of a single User account. To add such you will go to the resources packed and then add the following in the application.properties file.

in the user.name you can specify a username whereas in the user.password you will write the password. When adding this you will see the following login page, next time you try to access your REST API.

The REST API is now complete with Basic Authentication.