Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Development of a REST API in the Spring Boot Framework

DZone's Guide to

Development of a REST API in the Spring Boot Framework

Learn about the features of modern REST frameworks and why Spring Boot may be a good fit for your project, then look at a basic Spring Boot API setup.

Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

This article was written by Dario Carrasquel on the Admios blog.

Selecting the appropriate technologies is critical during the inception phase of a project. Most recently, we’ve been adopting a microservices architecture as a solution that satisfies our clients’ needs for modularity and availability.  

As a software engineer, one of our main tasks includes the evaluation of frameworks to develop REST APIs for our clients. The end goal was to reunite all their software services in a single-point access portal.

At the very beginning, selecting the right programming language for the backend was one of the main topics in every analysis of the project. Although Python, Scala, and Ruby were considered initially, a backward compatibility with core Java applications was the most important requirement. The evaluation was narrowed down to the available JVM compatible frameworks.

Features of Modern REST Frameworks in the Java Ecosystem

Spring Boot:

  • Fast development.
  • Mature libraries available and easier to integrate with third-party vendors.
  • Convention over configuration.
  • Microservices framework called Dropwizard that helps to instantly start and run Spring applications.
  • Embedded server.

Play!:

  • Modular architecture: similar to Ruby On Rails and Django.
  • Native support for Scala.
  • Asynchronous I/O and built-in hot reloading.

Lagom:

  • Service API supports asynchronous messaging and streaming by default. 
  • Hot reload development environment.
  • Consistent deployments across environments so services can be deployed, as they are, directly to production.
  • Persistence API manages the distribution of persisted entities across a cluster of nodes, enabling sharding and horizontal scaling.

Although all three options were more than adequate for the task, we decided to use Spring Boot because it relies heavily on the mature Spring Framework, which already contains many useful libraries that make project development easier. Also, there is plenty of documentation on the web for the majority of the topics involved in the framework usage.

Because of the already existing methods, the creation of a REST API in Spring Boot is quite straightforward. In order to demonstrate this, we developed a small application in a CRUD style for the management of our office’s soccer team. For data persistence, we used MongoDB and Jongo, the Java driver for queries in Mongo.

The first step was to create a Maven project. We had to add the dependencies for Spring Boot, MongoDB, Jongo and Swagger to document our API. The pom.xml looked like this.

To develop a REST endpoint in Spring Boot, we needed the main class as a starting point for the application and one or more models to represent the data objects.

We also needed a controller stereotype for the presentation layer, a service class, and a repository for the persistence layer. We used a MongoDB repository in this case, although we could have used any other classic DBMS.

Controller (seen below):

package com.admios.players.controller;

import com.admios.players.config.PlayersApplication;
import com.admios.players.model.Player;
import com.admios.players.service.PlayerService;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = PlayersApplication.API_V1, produces = MediaType.APPLICATION_JSON_VALUE)
public class PlayersController {

    public static final String ENDPOINT = "players";

    @Autowired
    private PlayerService service;

    @ApiOperation(value = "Register a new player", nickname = "Register a new player",
            notes = "Endpoint to register a new player. If the player already exists, the info will be updated"
                    + " with the submitted data.")
    @RequestMapping(value = ENDPOINT, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public HttpEntity<Player> registerPlayer(final @Validated @RequestBody Player player) {
        return new ResponseEntity<>(service.registerPlayer(player), HttpStatus.OK);
    }

    @ApiOperation(value = "Find the player details", nickname = "Find the player details",
            notes = "It will retrieve the player details")
    @RequestMapping(value = ENDPOINT + "/{name}", method = RequestMethod.GET)
    @ResponseBody
    public HttpEntity<Player> getPlayerDetails(@PathVariable String name) {
        Player player = service.findPlayerByName(name);
        return new ResponseEntity<>(player, player != null ? HttpStatus.OK: HttpStatus.NOT_FOUND);
    }

    @ApiOperation(value = "Delete the specified player", nickname = "Delete the specified player",
            notes = "It will delete the player specified in the request.")
    @RequestMapping(value = ENDPOINT + "/{name}", method = RequestMethod.DELETE)
    @ResponseBody
    public HttpEntity<Void> deleteCompany(@PathVariable String name) {
        return new ResponseEntity<>(service.deleteCompany(name) ? HttpStatus.OK : HttpStatus.NOT_FOUND);
    }
}

Service (seen below):

package com.admios.players.service;

import static com.admios.players.model.Player.PLAYER_NAME;
import static com.mongodb.client.model.Filters.eq;
import static com.admios.players.database.MongoUtils.filterToString;

import com.admios.players.database.MongoRepository;
import com.admios.players.model.Player;

import org.bson.types.ObjectId;
import org.jongo.MongoCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class PlayerService {

    private static final String COLLECTION = "players";

    @Autowired
    private MongoRepository repository;
    private MongoCollection players;

    @PostConstruct
    public void init() { players = repository.getCollection(COLLECTION); }

    public Player registerPlayer (Player player) {
        player.setId(null);
        Player dbPlayer = findPlayerByName(player.getName());

        if(dbPlayer == null) {
            players.save(player);
        } else {
            players.update(new ObjectId(dbPlayer.getId())).with(player);
            player.setId(dbPlayer.getId());
        }
        return player;
    }

    public Player findPlayerById(String id) { return players.findOne(new ObjectId(id)).as(Player.class); }

    public Player findPlayerByName(String name) {
        return players.findOne(filterToString(eq(PLAYER_NAME, name))).as(Player.class);
    }

    public boolean deleteCompany(String name) {
        Player player = findPlayerByName(name);
        if (player != null) {
            players.remove(new ObjectId(player.getId()));
            return true;
        }
        return false;
    }
}

Database

Application.properties

Finally, we ran the application and we accessed our endpoints from the interface displayed by Swagger at this URL: http://localhost:8080/swagger-ui.html.

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:
spring boot ,rest api ,integration ,software development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}