Path Parameters and Query Parameters in Micronaut

When building REST APIs, we often need to receive input from the user through URL parameters. This is very easy with Path Parameters and Query Parameters in Micronaut .

In this post, we will learn:

  • What are Path Parameters?
  • What are Query Parameters?
  • How to use them in Micronaut with simple real-life examples.
Path Parameters and Query Parameters in Micronaut

Our example will be based on a Library Management System using package: com.kscodes.library

What Are Path Parameters?

  • Path Parameters are part of the URL path.
  • Used to identify specific resources.

Example:

GET /books/123

123 is a path parameter representing the book ID.

What Are Query Parameters?

  • Query Parameters are added after a ? in the URL.
  • Used to filter, sort, or search.

Example:

GET /books?author=John&year=2023

author and year are query parameters.

Project Overview

We will create REST endpoints that allow us to:

  • Get a book by its ID (Path Parameter)
  • Search books by author and year (Query Parameters)

Step 1: Create Micronaut Project

Or generate using Micronaut Launch.

Step 2: Create Book Model

Create Book.java in: src/main/java/com/kscodes/library/model/

Step 3: Create Book Service

Create BookService.java in: src/main/java/com/kscodes/library/service/

Step 4: Create Book Controller

Create BookController.java in: src/main/java/com/kscodes/library/controller/

Step 5: Run and Test the Application

Build and run the project:

mvn mn:run

Add a Book

Get Book by ID (Path Parameter)

Search Books (Query Parameters)

Summary

  • Path Parameters are used for resource identification: /books/{id}
  • Query Parameters are used for searching/filtering: /books?author=John
  • Micronaut simplifies handling both using @Get, @QueryValue, and simple method arguments.