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


mn create-app com.kscodes.library --build maven --java-version 21

Or generate using Micronaut Launch.

Step 2: Create Book Model

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


package com.kscodes.library.model;

import java.util.UUID;

public class Book {

    private UUID id;
    private String title;
    private String author;
    private int year;

    public Book(String title, String author, int year) {
        this.id = UUID.randomUUID();
        this.title = title;
        this.author = author;
        this.year = year;
    }

    public UUID getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public int getYear() { return year; }
}

Step 3: Create Book Service

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


package com.kscodes.library.service;

import com.kscodes.library.model.Book;
import jakarta.inject.Singleton;
import java.util.*;
import java.util.stream.Collectors;

@Singleton
public class BookService {

    private final Map books = new HashMap<>();

    public Book addBook(String title, String author, int year) {
        Book book = new Book(title, author, year);
        books.put(book.getId(), book);
        return book;
    }

    public Optional getBook(UUID id) {
        return Optional.ofNullable(books.get(id));
    }

    public List searchBooks(String author, Integer year) {
        return books.values().stream()
                .filter(book -> (author == null || book.getAuthor().equalsIgnoreCase(author)))
                .filter(book -> (year == null || book.getYear() == year))
                .collect(Collectors.toList());
    }
}

Step 4: Create Book Controller

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


package com.kscodes.library.controller;

import com.kscodes.library.model.Book;
import com.kscodes.library.service.BookService;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.*;

import jakarta.inject.Inject;
import java.util.*;
import java.util.UUID;

@Controller("/books")
public class BookController {

    @Inject
    BookService bookService;

    // Add book (for testing)
    @Post("/")
    public Book addBook(@Body Map request) {
        String title = (String) request.get("title");
        String author = (String) request.get("author");
        int year = Integer.parseInt(request.get("year").toString());
        return bookService.addBook(title, author, year);
    }

    // Get book by ID (Path Parameter)
    @Get("/{id}")
    public HttpResponse getBook(UUID id) {
        return bookService.getBook(id)
                .map(HttpResponse::ok)
                .orElse(HttpResponse.notFound());
    }

    // Search books (Query Parameters)
    @Get("/")
    public List searchBooks(@QueryValue Optional author,
                                  @QueryValue Optional year) {
        return bookService.searchBooks(author.orElse(null), year.orElse(null));
    }
}

Step 5: Run and Test the Application

Build and run the project:

mvn mn:run

Add a Book


curl -X POST http://localhost:8080/books -H "Content-Type: application/json" -d '{"title":"Micronaut Guide","author":"John","year":2024}'

Get Book by ID (Path Parameter)


curl http://localhost:8080/books/{bookId}

Search Books (Query Parameters)


curl http://localhost:8080/books?author=John
curl http://localhost:8080/books?year=2024
curl http://localhost:8080/books?author=John&year=2024

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.