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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay