DEV Community

realNameHidden
realNameHidden

Posted on

4 1 1 1 1

With Spring can I make an optional path variable?


Yes, you can make a path variable optional in Spring by using @PathVariable with the required attribute set to false. However, for this to work, you also need to provide a default value or handle the absence of the variable in your logic.

Here are a few ways to handle optional path variables:

1. Using Default Path Without Variable

Define two endpoints: one with the variable and one without.

@RestController
@RequestMapping("/example")
public class ExampleController {

    @GetMapping
    public String handleWithoutPathVariable() {
        return "No path variable provided";
    }

    @GetMapping("/{id}")
    public String handleWithPathVariable(@PathVariable String id) {
        return "Path variable: " + id;
    }
}

Enter fullscreen mode Exit fullscreen mode

2. Using @PathVariable with required = false

This approach is possible when the path variable is declared in the URL template as optional (e.g., {id?} in Spring Boot 3+).

@RestController
@RequestMapping("/example")
public class ExampleController {

    @GetMapping({"/", "/{id}"})
    public String handleWithOptionalPathVariable(@PathVariable(required = false) String id) {
        if (id == null) {
            return "No path variable provided";
        }
        return "Path variable: " + id;
    }
}

Enter fullscreen mode Exit fullscreen mode
👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay