DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. Development of a REST API in Spring Boot Framework

Development of a REST API in Spring Boot Framework

Learn about the features of several popular REST frameworks in the JAVA ecosystem, and see how they can be used to build a REST API to connect services.

Dario Carrasquel user avatar by
Dario Carrasquel
·
Oct. 19, 17 · Tutorial
Like (3)
Save
Tweet
Share
15.18K Views

Join the DZone community and get the full member experience.

Join For Free

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 at Admios, one of our main tasks included the evaluation of frameworks to develop REST APIs for one of 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 back end 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, as well as synchronous.
  • 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:

- pom.xml

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.

- Main class

- Model

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 (or look 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 (or look 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

Spring Framework REST API Web Protocols Spring Boot Framework

Published at DZone with permission of Dario Carrasquel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 19 Most Common OpenSSL Commands for 2023
  • A Beginner’s Guide To Styling CSS Forms
  • Assessment of Scalability Constraints (and Solutions)
  • What Is JavaScript Slice? Practical Examples and Guide

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: