Spring Boot REST Controller example

In this tutorial we will learn how to create an example Spring Boot REST application which includes a Controller, a Repository and a main Application class.

Overview

Representational State Transfer (REST) is basically an architectural style for the web. REST specifies a set of constraints. These constraints ensure that clients (service consumers and browsers) can interact with servers in flexible ways.

Let’s first understand some common terminologies:

  • Server: Service provider. Exposes services which can be consumed by clients.
  • Client: Service consumer. Could be a browser or another system.
  • Resource: Any information can be a resource: a person, an image, a video, or a product you want to sell.
  • Representation: A specific way a resource can be represented. For example, the product resource can be represented using JSON, XML, or HTML. Different clients might request different representations of the resource.

Application Set up

Firstly, let’s bootstrap our application including the Web dependency. From the Spring Initializr, include the following dependency:

spring boot rest controller

Otherwise, bootstrap your project by using the spring shell command as follows:

spring init -dweb demo-rest

Next, import the Maven project in your favorite IDE and add a model class named Customer which is our Data Transfer Object:

public class Customer {
  private int id;
  private String name;

  public Customer(int id, String name) {
    super();
    this.id = id;
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }
}

Next, we will add our Spring Boot REST Controller:

@RestController
public class CustomerController {
  @Autowired
  CustomerRepository repository;

  @GetMapping("/list")
  public List<Customer> findAll() {
    return repository.getData();
  }

  @GetMapping("/one/{id}")
  public Customer findOne(@PathVariable int id) {
    return repository.getData().get(id);
  }

  @PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<Customer> create(@RequestBody Customer customer) {
    repository.saveCustomer(customer);
    return new ResponseEntity<>(customer, HttpStatus.CREATED);
  }
}
  • Firstly, the @RestController annotation is a combination of @ResponseBody and @Controller annotations. This is the simplest way to declare your REST Controllers.
  • Next, we are mapping our GET resources with @GetMapping which is a shortcut for @RequestMapping(method = RequestMethod.GET)
  • Finally, we include a @PostMapping which receives as input the Customer in JSON format and produces as well a Customer (in JSON format) in the Response. Please notice that Spring Boot will manage for you the marshalling and unmarshalling of the Customer object to JSON.

@GetMapping vs @RequestMapping

@GetMapping is a newer annotation for REST Controllers. You can apply @GetMapping only at method level. On the other hand, you can use @RequestMapping both at class level and as well as on your methods. The same goes for @PostMapping annotation.

More in detail, the CustomerController Endpoint has two methods:

  • findAll: which returns all the Customer objects
  • findOne: which returns a single Customer object
  • create: which adds a new Customer

We are using a Repository Class to store in memory the List of Customer object as follows:

@Component
public class CustomerRepository {
  List<Customer> customerList = new ArrayList<Customer>();

  @PostConstruct
  public void init() {
    customerList.add(new Customer(1, "frank"));
    customerList.add(new Customer(2, "john"));
  }

  public List<Customer> getData() {
    return customerList;
  }
  
  public void saveCustomer(Customer c) {
    customerList.add(c);
  }
}

Then, move to the shell and compile and package the application with:

$ mvn clean install 

Finally, you can run the application in any Spring Boot available way, f.e.

mvn spring-boot:run 

If you surf on http://localhost:8080/list, the list of Customer in JSON format will be displayed:

spring boot rest controller example

To add a new Customer object, you can use any REST Client or the curl command. Example:

curl -X POST http://localhost:8080/add -H 'Content-Type: application/json'   -d '{"id":"3","name":"Mark"}'

The source code for this tutorial is available on GitHub: https://github.com/fmarchioni/masterspringboot/tree/master/helloworld

Would you like to learn how to test this example with REST Assured? so check this: Testing Spring Boot with REST Assured