Creating a RESTful API in Micronaut

Micronaut is a popular framework for building lightweight and efficient microservices and serverless applications in Java, Kotlin, and Groovy. In this blog post, we will walk you through the process of creating a RESTful API using Micronaut. We’ll cover how to handle path variables, query parameters, request bodies, and combinations of these in your Micronaut controllers.

Prerequisites

Make sure you have a micronaut application up and running.

Adding a Controller

Create a class and add an Controller annotation

@Controller("/test")
class TestController {

    @Get("/{params}")
    suspend fun pathVariable(params: String?): String? {
        return params
    }
}

This will make sure your route to register and serve the data.

Handling Path Variables

Path variables are used to extract values from the URL’s path. Let’s create an endpoint that accepts a path variable.

    @Get("/{params}")
    suspend fun pathVariable(params: String?): String? {
        return params
    }
// http://localhost:8080/test/1

Here the variable name is used to match the value. On other hand you explicitly specify the micronaut using annotation

@Get("/explicit/{params}")
suspend fun pathVariableExplicit(@PathVariable params: String?): String? {
   return params
}
// http://localhost:8080/test/explicit/1

Handling Query Parameters

Query parameters are used to pass data to the server as part of the URL. Let’s create an endpoint that accepts query parameters.

@Get("/query-params")
    suspend fun queryParams(@QueryValue first: String?, @QueryValue second: String?): String? {
        return "$first $second"
    }

But consider if your query params is huge, It will hectic to add more number of parameters. To avoid that we should always use following format to take query parameter as input

@Get("/complex-query-params{?request*}")
    suspend fun complexQueryParams(request: ComplexInput): String? {
        return "${request.first} ${request.second}"
    }

Where ComplexInput is a data class

package com.example.common

import io.micronaut.core.annotation.Introspected

@Introspected
data class ComplexInput(
    var first: String?,
    var second: String?
)

Handling Request Bodies

You can also handle complex data sent in the request body. Let’s create an endpoint that accepts a JSON request body.

@Post("/post-body")
    suspend fun postBody(@Body request: ComplexInput): String? {
        return "${request.first} ${request.second}"
    }

Read Also: Micronaut HTTP Request Interceptors: A Comprehensive Guide

Implementation Detail: Rest API Controller

Conclusion:

In this blog, we’ve explored the essential concepts and techniques for writing a REST API in Micronaut, covering various aspects of handling different types of input. Whether it’s path variables, query parameters, request bodies, Micronaut provides a robust framework for building flexible and efficient APIs.

Related Post