05 - Spring Boot and Rest API

springboot
JPA
Rest API
A deeper explanation on Rest API usage
Author

ProtossGP32

Published

March 7, 2023

Introduction

Rest API in Spring Boot

@RestController

The Spring Boot annotation for the REST API controller. This annotation is responsible of converting the returned output to the expected plain-text format defined in the API documentation.

As with the @Controller, an endpoint is defined for this REST controller:

@RequestMapping("/path/to/api/endpoint")

Example:

@RequestMapping("/api/book")

REST API services

Types of data that the REST methods will return:

  • ResponseEntity<T Entity>: It’s a container that includes the following data:
    • HttpHeaders: info regarding the API (i.e. version) as well as the operation confirmation
    • Body content: it stores the Entity or the collection of Entity that we want to return

Additional tools

Swagger

From official page:

Swagger is a tool that tries to simplify API development. Swagger isn’t available as a Spring initializer dependency, so we have to install it via Maven Repository. Follow this article for Swagger integration in your Java project. This article is related to Swagger 2, if you want to user v3 (also known as OpenAPI 3.0), follow this other article.

Mockito

From official page:

Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with a clean & simple API. […] the tests are very readable and they produce clean verification errors.

Things to consider

Controller

  • It will deal with ResponseEntity<T> objects in the API methods to manipulate the HTTP response.
  • HttpHeaders object includes information related to the response:
    • operation: the API operation executed
    • version: the API version
    • operationStatus: whether the operation is successful or not
Where should we send the response information?

Taking into account the separation of concerns, it’s a good approach to include in the headers all the information regarding the outcome of the operation, while leaving the body for pure data objects.

Service

It will deal with Optional<T> types coming from the Repository interface. Optional types include either an object of the referenced type or a null, so they must be checked prior to its usage.