05 - Spring Boot and Rest API
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:
Example:
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 confirmationBody
content: it stores theEntity
or the collection ofEntity
that we want to return
Additional tools
Swagger
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
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 executedversion
: the API versionoperationStatus
: whether the operation is successful or not
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.