Creating REST Endpoints with @Controller and @Get/@Post in Micronaut (School Management Example)

Micronaut makes it very easy to create REST APIs using simple annotations. In this tutorial, we will explore how to use annotations like @Controller and @Get/@Post in Micronaut to build REST endpoints for a School Management System.

REST Endpoints with @Controller and @Get/@Post in Micronaut

Project Overview

We will build a simple School API that allows us to:

  • Add a student
  • View student details
  • List all students

Package structure: com.kscodes.school


Prerequisites

  • Java 21 installed
  • Micronaut CLI installed
  • Maven
  • VS Code or any IDE

Step 1: Create a Micronaut Project

Use Micronaut CLI to generate the project:

Or use Micronaut Launch and select Maven.

Open the project in VS Code.


Step 2: Create the Student Domain Class

Create Student.java in: src/main/java/com/kscodes/school/model/


Step 3: Create a Student Service

Create StudentService.java in: src/main/java/com/kscodes/school/service/


Step 4: Create REST Controller using @Controller, @Get and @Post

Create StudentController.java in: src/main/java/com/kscodes/school/controller/


Step 5: Run and Test the API

Build and run the application:

Add a Student

Get Student by ID

List All Students


Summary

  • Used @Controller to define REST endpoints
  • Used @Post for creating data
  • Used @Get for fetching data
  • Built a simple School Management REST API

This simple example shows how @Controller and @Get/@Post in Micronaut makes it easy to build REST APIs using annotations. In future posts, we will add persistence using databases, input validations, and advanced features!

You can also go through Building REST API in Micronaut (Banking App Example) for some more practice.