Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: A Validated Notes REST API

Build a complete Micronaut REST API: records, validation, a repository, a service, controllers, error handling and tests. With a runnable end-to-end Java stand-in.

In this project you put the chapter together: typed configuration, validation, layered code and tests. You will design a small Notes API with create, read, update, delete and search, then see how each part maps to Micronaut features.

The real Micronaut build is not available on this site, so the Micronaut code is shown read-only, ready to copy into a project made with the launcher. To practise the logic, there is a runnable stand-in that implements the same layers in plain Java, so you can run and change the behaviour here and then port it.

What you will build

Method and path Purpose Success Failure
GET /notes list notes, optional ?q= search and ?page= 200
GET /notes/{id} read one note 200 404
POST /notes create 201 400
PUT /notes/{id} replace 200 400, 404
DELETE /notes/{id} delete 204 404

The layers

Controller HTTP in and out, validation.
Service Rules and orchestration.
1 / 2

Step 1: create the project

Terminal
mn create-app com.example.notes --build=gradle --lang=java \
   --features=validation,data-jdbc,flyway,h2,serde-jackson

Pick the features you need; the launcher wires dependencies and plugins. If you are new to this, review Creating a Micronaut App and Project Structure and Configuration.

Step 2: model the data

Use a record for what the client sends and an entity for what you store, so the HTTP contract and the database schema can change independently:

Java
import io.micronaut.serde.annotation.Serdeable;
import jakarta.validation.constraints.*;

@Serdeable
public record NoteRequest(
        @NotBlank @Size(max = 80) String title,
        @NotBlank String body,
        @Min(1) @Max(5) int priority) {}

@Serdeable
public record NoteView(long id, String title, String body, int priority) {}

The validation annotations are explained in Bean Validation.

Step 3: repository and service

With Micronaut Data you declare an interface and the implementation is generated at compile time:

Java
import io.micronaut.data.annotation.*;
import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;

@MappedEntity("notes")
public record NoteEntity(@Id @GeneratedValue Long id, String title, String body, int priority) {}

@JdbcRepository(dialect = Dialect.H2)
public interface NoteRepository extends CrudRepository<NoteEntity, Long> {
    java.util.List<NoteEntity> findByTitleContainsIgnoreCase(String text);
}
Java
@Singleton
public class NoteService {
    private final NoteRepository repository;
    public NoteService(NoteRepository repository) { this.repository = repository; }

    public NoteView create(NoteRequest r) {
        return view(repository.save(new NoteEntity(null, r.title(), r.body(), r.priority())));
    }
    public Optional<NoteView> find(long id) { return repository.findById(id).map(this::view); }
    private NoteView view(NoteEntity e) { return new NoteView(e.id(), e.title(), e.body(), e.priority()); }
}

The service is a plain class that takes its repository through the constructor, so it can be unit tested with a fake.

Step 4: the controller

Java
@Validated
@Controller("/notes")
class NoteController {
    private final NoteService service;
    NoteController(NoteService service) { this.service = service; }

    @Post
    @Status(HttpStatus.CREATED)
    NoteView create(@Body @Valid NoteRequest request) { return service.create(request); }

    @Get("/{id}")
    HttpResponse<NoteView> get(long id) {
        return service.find(id).map(HttpResponse::ok).orElseGet(HttpResponse::notFound);
    }
}

Invalid bodies are rejected with 400 before the method runs. Consider a global @Error handler to give every failure the same JSON shape.

Step 5: configuration and tests

Put the page size in typed configuration (see Typed Configuration), use application-test.yml for an in-memory database, and test through the HTTP client as in Testing with Micronaut Test.

Try it: the whole API in plain Java

Run this program to see the layers working together: validation, repository, service and a router that returns status codes. Change a rule and re-run.

Java Notes API end to end (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Extensions to try

  • Add pagination with Pageable and return a Page<NoteView>.
  • Add an @Error handler that maps ConstraintViolationException to a consistent JSON body.
  • Protect the API with @Secured and give each note an owner (see the next project).
  • Expose /health and metrics as in Metrics, Health and Tracing.
  • Build a native image and compare startup time with the JVM (GraalVM Native Image Basics).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why separate the request record from the stored entity?

    Separate types prevent clients from setting fields such as the id and decouple API from storage.
  2. 2. What does Micronaut Data generate for a @JdbcRepository interface?

    Query methods are turned into code during compilation, so there is no runtime reflection.
  3. 3. What status does a successful DELETE normally return?

    204 No Content means the deletion succeeded and there is no body.
  4. 4. Where should the rule that a title is not blank live?

    Declaring it on the data lets the framework reject bad input at the edge.

Summary

  • Layer the app: controller, service, repository, records.
  • Validate input at the edge and map failures to 400, 404 and 204 correctly.
  • Micronaut Data generates repositories at compile time.
  • Test through the HTTP client and keep configuration typed.

Next: Project: A Secured Inventory Service