Availability Disclaimer

This article can be found on other sources:

Spring Boot logo

Spring Boot is a web framework built on top of the framework Spring. It is designed for easier use and quicker implementation. It does so by configuring the application and its environment as automatically as possible. As a newcomer, I can say that it makes the framework really easy to get into.

My learning led me to read most of the reference documentation, which is well written and gives you a lot of insights into the internal behavior of Spring Boot. This documentation gives a lot of details, so this article aims to take the counter approach and pinpoint the concepts you will need to implement an API using Spring Boot. I will complement each section with a set of links to related documentation, may you want to dig further.

As a side note, this document will be using version 2.4.2 of the framework, on a Java project using Gradle as the build system. However, the information remains applicable to any compatible language and build system.

This article will cover the following aspects of creating an API with Spring Boot:

  • Bootstrap the project
  • Create REST endpoints
  • Handle errors
  • Connect to a persistence layer
  • Paginate the results
  • Test the application
  • Package the Application

Bootstrap the project

This part may be the easiest, as Spring Boot is providing a package generator at https://start.spring.io/. We can select all required modules and retrieve an archived project with the build system, dependencies, and main application class.

Outside of this generator, to declare a RESTful API, our project should define the Spring Boot starter web dependency. The starter dependencies are a set of ready to use features packaged by Spring Boot.

1plugins {
2  id 'org.springframework.boot' version '2.4.2'
5dependencies {
6  implementation 'org.springframework.boot:spring-boot-starter-web'

The application’s main method should be contained in any class, on which we should apply the annotation @SpringBootApplication. This annotation is responsible for a lot of automatic configurations, namely the components injection and web server startup.

2public class MyApplication {
3    public static void main(String[] args) {
4        SpringApplication.run(MyApplication.class, args);
5    }

Starting the server is as simple as using the embedded command ./gradlew bootRun. The server will start, but we don’t have any endpoint to serve at the moment.

Documentation links:


List of starter dependencies

Create a REST endpoint

To create a controller, we simply have to annotate any class with @RestController. We can then configure any method inside this controller as an endpoint using @RequestMapping.

@RequestMapping help us configuring the endpoint by providing an URL, the HTTP verb, the expected data type, and more. It can be applied both on a class and a method, the configurations applied on the class will be inherited by the methods underneath and the path concatenated.

To control our endpoint status codes we will return aResponseEntity, holding both the response message and HttpStatus.

 2@RequestMapping(value = "/hello",
 3        consumes = MediaType.ALL_VALUE,
 4        produces = MediaType.APPLICATION_JSON_VALUE)
 5public class HelloWorldController {
 7    @RequestMapping(value = "/world", method = RequestMethod.GET)
 8    public ResponseEntity<Map<String, String>> index() {
 9        HashMap<String, String> output = new HashMap<>();
10        output.put("message", "Hello World!");
11        return new ResponseEntity<>(output, HttpStatus.OK);
12    }

The ResponseEntity will be automatically transformed to an HTTP response, using the HttpStatus as response code and transforming the message to a JSON object. On top of transforming Maps to JSON objects, Spring Boot configure Jackson to map all public attributes or getters of any class to a JSON object.

1$ curl -i "localhost:8080/hello/world"
2HTTP/1.1 200

Documentation links:

@RestController and @RequestMapping

@RequestMapping API doc

Customize Json Serialization

Advanced endpoint configuration

Now that we have a controller, we may want to define dynamic HTTP endpoints. To do so, the main annotations to keep in mind are:

  • @RequestBody : Defines a body structure through a java Class.
  • @PathVariable: Defines a variable subpart of the endpoint URL.
  • @RequestParam : Defines a query parameter.

The controller below showcases the three annotations with two endpoints, each returning a custom “Hello World” depending on the query.

 2@RequestMapping(value = "/hello",
 3        consumes = MediaType.ALL_VALUE,
 4        produces = MediaType.APPLICATION_JSON_VALUE)
 5public class HelloWorldController {
 7    // The behavior is not representative of a typical POST request
 8    // and only here as a matter of example.
 9    @RequestMapping(value = "", method = RequestMethod.POST)
10    public ResponseEntity<Map<String, String>> greetFromBody(@RequestBody HelloBody helloBody) {
11        HashMap<String, String> output = new HashMap<>();
12        output.put("message", "Hello " + helloBody.getName());
13        return new ResponseEntity<>(output, HttpStatus.OK);
14    }
16    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
17    public ResponseEntity<Map<String, String>> greet(@PathVariable String name,
18                                                     @RequestParam(required = false,
19                                                                   defaultValue = "0") int amount_exclamation) {
20        HashMap<String, String> output = new HashMap<>();
21        StringBuilder b = new StringBuilder("Hello ");
22        b.append(name);
23        for (int i = 0; i < amount_exclamation; i++) {
24            b.append("!");
25        }
26        output.put("message", b.toString());
27        return new ResponseEntity<>(output, HttpStatus.OK);
28    }
31class HelloBody {
32    String name;
34    public HelloBody() {
35        // Used by Jackson
36    }
38    public String getName() {
39        return this.name;
40    }

The endpoints defined above can be used as follows:

1curl -i "localhost:8080/hello/jack?amount_exclamation=4"
2HTTP/1.1 200
3{"message":"Hello jack!!!!"}
5# -d automatically creates a POST request.
6$ curl -i "localhost:8080/hello" -d '{"name": "Bob"}' -H "Content-Type: application/json"
7HTTP/1.1 200
8{"message":"Hello Bob"}

Documentation links:




Handle errors

By default, Spring Boot will return the HTTP code 200 for any successful request, 404 if the endpoint is not registered, and 500 for any error. We already saw that using ResponseEntity enables us to override this behavior for successful requests, but we still need to handle error codes more finely.

To do so, we will define custom API exceptions that will be automatically transformed into HTTP codes. This transformation is done by a class extending ResponseEntityExceptionHandler and annotated with @ControllerAdvice. In this class, we can define methods to handle exceptions using the annotations @ExceptionHandler and @ResponseStatus.

 2public class MyApplicationControllerAdvice extends ResponseEntityExceptionHandler {
 4    @ExceptionHandler(ApiException.class)
 5    @ResponseStatus(HttpStatus.BAD_REQUEST)
 6    public void handleBadRequest() {
 7    }
 9    @ExceptionHandler(NotFoundException.class)
10    @ResponseStatus(HttpStatus.NOT_FOUND)
11    public void handleNotFound() {
12    }
15public class ApiException extends Exception {
18public class NotFoundException extends ApiException {

After defining the ControllerAdvice in your project, any exception thrown by your controllers will be parsed and transformed to the bound ResponseStatus.

 2@RequestMapping(value = "/exception")
 3public class ExceptionController {
 5    @RequestMapping(value = "/404", method = RequestMethod.GET)
 6    public ResponseEntity<Map<String, String>> notFound() throws NotFoundException {
 7        throw new NotFoundException();
 8    }    
10    @RequestMapping(value = "/400", method = RequestMethod.GET)
11    public ResponseEntity<Map<String, String>> badRequest() throws ApiException {
12        throw new ApiException();
13    }
15    @RequestMapping(value = "/500", method = RequestMethod.GET)
16    public ResponseEntity<Map<String, String>> ise() throws Exception {
17        throw new Exception();
18    }
1$ curl -i "localhost:8080/exception/500"
2HTTP/1.1 500
4$ curl -i "localhost:8080/exception/404"
5HTTP/1.1 404
7$ curl -i "localhost:8080/exception/400"
8HTTP/1.1 400

Our exception handling is very simple and does not return any payload, but it is possible to implement exception parsing in the methods of ResponseEntityExceptionHandler.

Documentation links:





Connect to a persistence layer


To use a database, we will need the Java Persistence API (JPA) package and the implementation of any persistence layer. The former will install interface APIs, while the latter will provide the implementations and drivers.

To pinpoint the minimal changes required to switch between two distinct databases, we will show the integration with both PostgreSQL and H2 at the same time. First, let’s declare our dependencies:

1dependencies {
2  implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
4  // Dependencies to your used dbms
5  implementation 'org.postgresql:postgresql:42.2.1'
6  implementation 'com.h2database:h2:1.4.200'

The second step is to configure the accesses in application.properties. The property file is the first and the last time we will have to worry about our persistence configuration. In this file, the 3 lines commented out are the only part to change to switch from PostgreSQL to H2.

 4# Automatically create & update the database schema from code.

Documentation links:

Database configuration

Available properties

Define a model

Defining a model is as simple as using annotations defined on JSR-317. These annotations are available through the package javax.persistence, which is available through the JPA dependency.

For instance, the code below creates a Delivery entity. Our entity identifier is the field id, which will be automatically initialized and increased on each new saved entity in the database thanks to the annotation @GeneratedValue.

Note: All attributes publicly available will be set into the JSON representation of the entity in the API responses.

 2@Table(name = "delivery")
 3public class Delivery {
 4    @Id
 5    @GeneratedValue(strategy = GenerationType.AUTO)
 6    long id;
 8    @Column(nullable = false)
 9    @NotNull
10    @Enumerated(EnumType.STRING)
11    DeliveryState state;
13    @Column(nullable = false)
14    @NotNull
15    String location;
17    public Delivery() {
18        // Used by Jackson2
19    }
21    public Delivery(@NotNull DeliveryState state, @NotNull String location) {
22        this.state = state;
23        this.location = location;
24    }
26    public long getId() {
27        return id;
28    }
30    public DeliveryState getState() {
31        return state;
32    }
34    public void setState(DeliveryState state) {
35        this.state = state;
36    }
38    public String getLocation() {
39        return location;
40    }
42    public void setLocation(String location) {
43        this.location = location;
44    }
47enum DeliveryState {

To ensure consistency of our data class, we applied @NotNull validations from JSR-303, these validations can be enforced on endpoints as we will see during the next section. The constraints are contained in the package javax.validation.constraints, available through the dependency spring-boot-starter-validation.

1dependencies {
2  implementation 'org.springframework.boot:spring-boot-starter-validation'

Documentation links:

Entity Declaration

javax.persistence API documentation (@Entity, @Column, @Enumerate, …)


javax.validation.constraints API documentation (@NotNull)

Expose the model

To interact with our models, we have to define a Repository, for instance, a CrudRepository. Doing so is as easy as extending the class with an empty class. Spring Boot will automatically implement functions to interact with the entity.

2public interface DeliveryRepository extends CrudRepository<Delivery, Long> {

We annotate this component @Repository to make it available to dependency injection. Then we can inject and use the repository in any class, for example directly in a controller. Using@Autowired will automatically retrieve the @Repository declared above_._

Note: _@Repository_ and _@Service_ behave exactly as the main injection annotation_@Component_, it simply enables to mark a semantic difference.

 2@RequestMapping(value = "/delivery",
 3        consumes = MediaType.APPLICATION_JSON_VALUE,
 4        produces = MediaType.APPLICATION_JSON_VALUE)
 5public class DeliveryController {
 7    private final DeliveryRepository deliveryRepository;
 9    @Autowired
10    public DeliveryController(DeliveryRepository deliveryRepository) {
11        this.deliveryRepository = deliveryRepository;
12    }
14    @RequestMapping(value = "", method = RequestMethod.POST)
15    public ResponseEntity<Delivery> post(@Valid @RequestBody Delivery delivery) throws ApiException {
16        try {
17            delivery = deliveryRepository.save(delivery);
18        } catch (Exception e) {
19            throw new ApiException();
20        }
21        return new ResponseEntity<>(delivery, HttpStatus.OK);
22    }
24    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
25    public ResponseEntity<Delivery> get(@PathVariable long id) throws ApiException {
26        Optional<Delivery> delivery = deliveryRepository.findById(id);
27        if (delivery.isEmpty()) {
28            throw new NotFoundException();
29        }
30        return new ResponseEntity<>(delivery.get(), HttpStatus.OK);
31    }

We used the annotation@Valid to ensure that our constraints defined above are met on the sent Delivery body.

 1$ curl -i "localhost:8080/delivery" -H 'Content-Type: application/json' \
 2  -X POST -d '{"state": "PENDING"}'                  
 3HTTP/1.1 400 
 5$ curl -i "localhost:8080/delivery/1" -H 'Content-Type: application/json'
 6HTTP/1.1 404 
 8$ curl -i "localhost:8080/delivery" -H 'Content-Type: application/json' \
 9  -X POST -d '{"state": "PENDING", "location":"Budapest"}'
10HTTP/1.1 200 
13$ curl -i "localhost:8080/delivery/1" -H 'Content-Type: application/json'                                                                                 13014HTTP/1.1 200

Note: H2 is an in-memory database so the data will be wiped out at each server restart.

Documentation Links:

CrudRepository API Documentation

Spring Component Declaration

javax.validation API documentation (@Valid)

Paginate the results

This section illustrates how well Spring Boot integrates some classic features of a web API. To paginate the access to our previous entity Delivery, we simply have to change the repository’s extended class from CrudRepository to PagingAndSortingRepository.

2public interface DeliveryRepository extends PagingAndSortingRepository<Delivery, Long> {

This repository implementation provides a new method findAll(Pageable) returning a Page. The class Pageable configures the page and page size to return.

 2@RequestMapping(value = "/delivery",
 3        consumes = MediaType.APPLICATION_JSON_VALUE,
 4        produces = MediaType.APPLICATION_JSON_VALUE)
 5public class DeliveryController {
 7    private final DeliveryRepository deliveryRepository;
 9    @Autowired
10    public DeliveryController(DeliveryRepository deliveryRepository) {
11        this.deliveryRepository = deliveryRepository;
12    }
14    @RequestMapping(value = "", method = RequestMethod.GET)
15    public ResponseEntity<Page<Delivery>> index(@RequestParam(required = false, defaultValue = "0") int page) {
16        Pageable pageable = PageRequest.of(page, 50);
17        return new ResponseEntity<>(deliveryRepository.findAll(pageable), HttpStatus.OK);
18    }

The endpoint will then serve the whole Page object’s data upon request.

 1$ curl "localhost:8080/delivery" -H 'Content-Type: application/json' | jq                                                                                   4 2{
 3  "content": [
 4    {
 5      "id": 1,
 6      "state": "PENDING",
 7      "location": "Budapest"
 8    }
 9  ],
10  "pageable": {
11    "sort": {
12      "sorted": false,
13      "unsorted": true,
14      "empty": true
15    },
16    "offset": 0,
17    "pageNumber": 0,
18    "pageSize": 50,
19    "paged": true,
20    "unpaged": false
21  },
22  "totalPages": 1,
23  "totalElements": 1,
24  "last": true,
25  "first": true,
26  "size": 50,
27  "number": 0,
28  "sort": {
29    "sorted": false,
30    "unsorted": true,
31    "empty": true
32  },
33  "numberOfElements": 1,
34  "empty": false

Documentation links:

PagingAndSortingRepository API Documentation

PageRequest API Documentation

Page API Documentation

Test the application

Spring Boot provides every tool to easily test controllers with a set of APIs and mocks. Mostly, MockMvc will enable us to send requests and assert response content without having to worry about technicalities.

As an example, we are testing the POST endpoint from the section above. One of these tests is successfully creating a Delivery entity, and the second one simulates an error coming from the database.

To avoid relying on a physical instance of a persistence layer, we injected our DeliveryRepository instance using @MockBean, which creates and injects a mock of our component.

 3class DeliveryControllerTest {
 4    @Autowired
 5    private MockMvc mvc;
 7    @MockBean
 8    DeliveryRepository deliveryRepository;
10    @Test
11    void testPostDeliveryOk() throws Exception {
12        ObjectMapper mapper = new ObjectMapper();
13        Map<String, String> delivery = getValidDelivery();
14        String body = mapper.writeValueAsString(delivery);
15        MockHttpServletRequestBuilder accept =
16                MockMvcRequestBuilders.post("/delivery")
17                        .accept(MediaType.APPLICATION_JSON)
18                        .contentType(MediaType.APPLICATION_JSON)
19                        .content(body);
20        mvc.perform(accept).andExpect(status().isOk());
21    }
23    @Test
24    void testPostPersistIssue() throws Exception {
25        ObjectMapper mapper = new ObjectMapper();
26        Map<String, String> delivery = getValidDelivery();
27        String body = mapper.writeValueAsString(delivery);
28        Mockito.when(deliveryRepository.save(Mockito.any())).thenThrow(new RuntimeException());
30        MockHttpServletRequestBuilder accept =
31                MockMvcRequestBuilders.post("/delivery")
32                        .accept(MediaType.APPLICATION_JSON)
33                        .contentType(MediaType.APPLICATION_JSON)
34                        .content(body);
36        mvc.perform(accept).andExpect(status().is4xxClientError());
37    }
39    private Map<String, String> getValidDelivery() {
40        Map<String, String> delivery = new HashMap<>();
41        delivery.put("state", "PENDING");
42        delivery.put("location", "Rome");
43        return delivery;
44    }

Documentation links:




MockMvc api Documentation

Package the application

Spring boot also eases the application packaging either as a standalone jar or a docker image.

  • To create a ready to run fat jar, execute ./gradlew bootJar.
  • To build a docker image, execute ./gradlew bootBuildImage.

Note that docker does not like uppercase characters in the image name, but we can easily customize the image name and version.

1// Only use lowercase on docker image name
2tasks.named("bootBuildImage") {
3    imageName = "${rootProject.name.toLowerCase()}:${version}"

Documentation links:

Create an application fat jar

Configure Docker Image


Spring Boot can be used with a handful of annotations and will manage most of the configuration for you. However, most of the configuration can be overridden to provide your own behavior if necessary. This makes it a good framework to design proof of concepts while keeping room for optimization if the project grows specific needs.

If you want to know more about the framework, I can’t stress enough the quality of the Reference Documentation, which gives really good details.

If you want to play around with some code, you can find all those concepts on an example delivery API on GitHub.