Courses
Module 1. Initialize Project
Module 2. REST services

Create Controllers

Create Controllers

In this lesson, we will learn how to create controllers for our Book and Author entities.

In the current implementation we will hardcode responses. In later lessons we will learn how to use an in-memory repository to manage data persistence. Then we will learn how to use a database to persist data.

Here are some points for creating controllers:

  • use a separate controller package
  • use the /api/<plural-entity> prefix for endpoints
  • use the @RestController annotation to automatically convert the response of the controller method to an HTTP response

List of controller methods for each entity:

Controller MethodHTTP MethodEndpointRequest bodyResponse bodyResponse status codeDescription
list()GET/-list of DTO200 OKGet list of all entities
get(id)GET/{id}-DTO200 OKGet one entity by UUID
create(dto)POST/SaveDTODTO201 CREATEDCreate new entity
update(id, dto)PUT/{id}SaveDTODTO200 OKUpdate existing entity
delete(id)DELETE/{id}--204 NO CONTENTDelete entity

Here are the implementation details for each controller method. Note: the logic is hardcoded now; later, we will persist the data.

Controller MethodNotes
list()Response is hardcoded
get(id)Use id from response, hardcode other fields
create(dto)Data is not persisted, return created entity
update(id, dto)Data is not persisted, return updated entity
delete(id)Data is not deleted

AuthorController

import com.romach007.spring_boot_web_mvc.dto.AuthorDTO;
import com.romach007.spring_boot_web_mvc.dto.SaveAuthorDTO;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/authors")
public class AuthorController {

    @GetMapping
    public List<AuthorDTO> list() {
        return List.of(
            new AuthorDTO(UUID.fromString("c77eff4d-d6c0-4386-9c8e-9e6e7b0d9c55"), "John Doe")
        );
    }

    @GetMapping("/{id}")
    public AuthorDTO get(@PathVariable UUID id) {
        return new AuthorDTO(id, "John Doe");
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public AuthorDTO create(@RequestBody SaveAuthorDTO dto) {
        return new AuthorDTO(UUID.randomUUID(), dto.getName());
    }

    @PutMapping("/{id}")
    public AuthorDTO update(@PathVariable UUID id, @RequestBody SaveAuthorDTO dto) {
        return new AuthorDTO(id, dto.getName());
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable UUID id) {}
}

BookController

import com.romach007.spring_boot_web_mvc.dto.AuthorDTO;
import com.romach007.spring_boot_web_mvc.dto.BookDTO;
import com.romach007.spring_boot_web_mvc.dto.SaveBookDTO;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/books")
public class BookController {

    @GetMapping
    public List<BookDTO> list() {
        return List.of(
            new BookDTO(
                UUID.fromString("7acf89b7-7aaf-4a8c-bb98-1d85ea7d0e96"),
                "Book Title",
                "978-3-16-148410-0",
                "description",
                List.of(
                    new AuthorDTO(UUID.fromString("c77eff4d-d6c0-4386-9c8e-9e6e7b0d9c55"), "John Doe")
                ),
                LocalDate.parse("2007-12-03")
            )
        );
    }

    @GetMapping("/{id}")
    public BookDTO get(@PathVariable UUID id) {
        return new BookDTO(
            id,
            "Book Title",
            "978-3-16-148410-0",
            "description",
            List.of(
                new AuthorDTO(UUID.fromString("c77eff4d-d6c0-4386-9c8e-9e6e7b0d9c55"), "John Doe")
            ),
            LocalDate.parse("2007-12-03")
        );
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public BookDTO create(@RequestBody SaveBookDTO dto) {
        return new BookDTO(
            UUID.randomUUID(),
            dto.getTitle(),
            dto.getIsbn(),
            dto.getDescription(),
            dto.getAuthorIds().stream().map(id -> new AuthorDTO(id, "John Doe")).toList(),
            dto.getPublicationDate()
        );
    }

    @PutMapping("/{id}")
    public BookDTO update(@PathVariable UUID id, @RequestBody SaveBookDTO dto) {
        return new BookDTO(
            id, dto.getTitle(),
            dto.getIsbn(),
            dto.getDescription(),
            dto.getAuthorIds().stream()
                .map(authorId -> new AuthorDTO(authorId, "John Doe"))
                .toList(),
            dto.getPublicationDate()
        );
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable UUID id) {}
}