RESTful API: Java Spring Boot Implementation

 In Self-Development, Tech Corner

API or application programming interface is a set of functions and procedures which enables access for the features, or the data in an application. REST is an architectural principle for creating APIs. It uses HTTP as a protocol for delivering data. When creating a web application, we must define the hidden parts from the end users and the ones that are publicly available. The URLs of an application are part of the interface or the API of the app itself. So when a user accesses them, they will retrieve certain sets of data. In other words, execute an action and notify the user of the result.  The underlying protocol of the world wide web is actually REST. When compared to the SOAP API, REST is faster and more efficient because it requires less bandwidth for data transfer.

1. Design principles established in REST

Uniform interface

The interface must have uniform naming convention. The URLs for the resources need to specify the resource. Example: If the URL is used to create a new user with name=Alex, the url would look something like: …/application/users/create?name=Alex

Stateless interaction

The server does not store any of the client state.

Cacheable

The methods and responses can be additionally cached. This way, when a resource often accessed can be kept in the cache and retrieved in a fast and effective way.

Client-Server

The web services have their own query parameters, URL, request body and headers. This can specify the authentication and authorization for the service. The client is unaware of how the server works. Also, the server is unaware of the context in which the client accesses the server.

Layered system

The system configuration can contain more than one server. Eg. A load balancer that will delegate the requests to the main server. This enforces the security strategies of the server. The client will not know whether he is communicating with the main server or with one of the intermediate servers.

Code on demand

This is the only optional constraint for REST. The client gets a piece of code (can be java script, applet, html etc.), which he/she will use to communicate with the server. Eg. Retrieving the code used for encrypting the communication between the client and the server.

2. METHODS OF RESTFUL APPLICATION

  • GET method – retrieves a resource.
  • POST method — creates a new resource, from the body of the request. Each request can contain a payload or a body, used for creating the data for the resource in the application.
  • PUT method — updates an existing resource.
  • DELETE method — deletes an exciting resource in the application.

The methods can also specify query parameters, added at the end of the URL. The methods can have an XML, JSON, PDF, text file, HTML page or other file type in the request body. The result of the method can also be in any of the above mentioned formats. Usually, when using REST, the methods in the API produce and consume JSON formats. But it is not forbidden to use any of the other types. SOAP web services are the older alternative for communication over HTTP and they work with XML data.

3. IMPLEMENTATION OF REST SERVICES – example

In order to follow this, you need to have installed JDK (java development kit) version 8 or higher and Maven or Gradle.

Create a new Spring boot project

We will create a new maven project. Specify the
– group id (example: com.test)
– the artifact id, which is the name of the project (SpringRest in our case).

InteliJ and Eclipse both offer creating a new maven project with a few clicks. Do not use any of the templates, create a new project from the wizard. After the completion of the wizard, the project will have a file named pom.xml. In this file we need to insert the code snippet provided from the official spring site. Now, change the “external libraries” module, as it will include the new spring libraries. See the project structure in the picture below:

maven-project-structure

Add the following code to your pom.xml (taken from Spring.io):

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Build the maven project, or simply import the changes. After that the External libraries module should look something like this:

External libraries for Spring Boot

Create the REST controller

Create a new package in the “src” directory, named “java”, if there isn’t one already. In the java package we will be writing all of the code for the app. Following conventions for web development, we will create the following package structure:

  • controller
  • dao
  • service
  • entity

Always keep in mind the naming convention for packages. The packages should be named according to the group id of the maven project.

Package structure for the project

In the controller package we will be adding our REST components. Creating a class with annotation “@RestController”, we have created our first REST service. First, we will create the entity class, in this case the Example class, with three simple fields.

package com.example.entity;

public class Example {

    private int id;
    private String name;
    private String type;

    public Example(int id, String name, String type) {
        this.id = id;
        this.name = name;
        this.type = type;
    }

}

Applying DAO design patterns

In previous blog posts, we  discussed the DAO design pattern, so here we will see it in action. We give the DAO class a Repository annotation because it will access the repository to fetch the Example objects. In real case scenarios, the list of examples will be filled with real data fetched from the database. But in this example we simply add elements in a static block to demonstrate the controller and its functions.

@Repository
public class ExampleDao {

    private static List<Example> examples;

    static{
        examples=new ArrayList<>();
        examples.add(new Example(0,"Test","test"));
    }

    public Collection<Example> getAllExamples(){
        return examples;
    }

}

In the service class we simple add the DAO class and use the methods from it. We annotate it with the Service annotation, so it can be autowired in the controller class.

@Service
public class ExampleService {

    private ExampleDao exampleDao;
    public Collection<Example> getAllExamples(){
        return exampleDao.getAllExamples();
    }

}

And finally, for creating the REST controller, we use the RestController annotation. Additionally we can specify the path by adding the annotation RequestMapping, while in the brackets we add the path value. The methods in the controller class can specify the request mapping. Eg. with this annotation we specify the Request Method and also, the path to the method.

@RestController
@RequestMapping("/examples")
public class ExampleController {

    @Autowired
    private ExampleService exampleService;

    @RequestMapping(value="/all",method= RequestMethod.GET)
    public Collection<Example> listExamples(){
        return exampleService.getAllExamples();
    }
}

For the application to work, we need to create a main class which will start the Spring Boot Application. The main class will have SpringBootApplication annotation and in its main method needs to run the application.

@SpringBootApplication
public class Main {

    public static void main(String[] args){

        SpringApplication.run(Main.class,args);

    }
}

By simply running the main class, the web project is started with an interface that can be accessed via browser. Point to the localhost:8080 address and the path value we created in the controller and it will return the collection of examples. The path to the method will also include the path value for the class in which is defined.

REST service for retrieving all the examples

Cover Image by Alvaro Reyes on Unsplash

Recommended Posts
java developer

SINGULAR STORY IN YOUR INBOX

Get news about career opportunities and product updates once a month.