Spring Boot @PathVariable Annotation Explained with Real-Time Examples | REST API

Introduction :

In my previous blog, I explained how we use @RequestParam in Spring Boot to handle query parameters in REST APIs.

While building real backend applications, I realized that another very commonly used annotation is @PathVariable.

In this article, I’ll share my real experience with @PathVariable, where I used it in actual APIs, why it is important, and how it differs from @RequestParam.


What is @PathVariable?

In real Spring Boot development, I usually use @PathVariable when I need to fetch or perform operations on a specific resource using its ID or unique value directly from the URL.

Instead of passing values as query parameters, the data comes directly from the URL path itself.

This makes the API look more clean and REST-friendly.


Real-Time Code Example

In one of my backend implementations, I used @PathVariable like this:

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public String getUserById(@PathVariable("id") int userId) {
        return "Fetched user details for ID: " + userId;
    }
}

Output

If I call:

GET /users/101

Response:

Fetched user details for ID: 101

This was one of the simplest but most useful patterns I used in real projects.


Real-Time Use Cases I Worked On

In real backend development, I used @PathVariable in multiple scenarios:

1. Fetch User Details

@GetMapping("/users/{id}")
public String getUser(@PathVariable int id) {
    return "User fetched: " + id;
}

2. Delete User by ID

@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable int id) {
    return "User deleted successfully with ID: " + id;
}

3. Fetch Nested Resource (Real API Structure)

@GetMapping("/orders/{orderId}/users/{userId}")
public String getOrderInfo(
        @PathVariable int orderId,
        @PathVariable int userId) {

    return "Order ID: " + orderId + ", User ID: " + userId;
}

This helped me understand how real-world REST APIs are structured in enterprise applications.


When I Prefer @PathVariable

From my experience, I usually prefer @PathVariable in these cases:

  • When working with a specific resource

  • When designing clean REST APIs

  • For operations like GET, DELETE, or UPDATE by ID

  • When the value is part of the resource identity

Example patterns:

/users/1
/products/10
/orders/500

This makes APIs more readable and REST-standard.


Mistake I Made (Important Learning)

At one point, I made a small mistake like this:

@GetMapping("/users/{id}")
public String getUser(@PathVariable("userId") int id)

This caused a runtime issue because the path variable name didn’t match.

Correct is:

@PathVariable("id")

This taught me an important lesson:
Spring is strict about path variable mapping, and even small naming mistakes can break the API.


Key Learnings from My Experience

  • @PathVariable helps build clean and RESTful APIs

  • It is best suited for identifying specific resources

  • It is widely used in real backend systems

  • Small naming mistakes can lead to runtime errors


Interview Tip:

When interviewers ask:

Difference between @PathVariable and @RequestParam?

I usually explain it like this:

  • @PathVariable → used to identify a specific resource in the URL

  • @RequestParam → used for filters, search, or optional query values

This simple explanation with example works well in interviews.


Conclusion :

While working on Spring Boot projects, I realized that @PathVariable plays an important role in designing clean and meaningful REST APIs.

It helped me structure endpoints in a more readable way and follow real-world API standards.

If you are building REST APIs, understanding @PathVariable properly will definitely improve your API design and coding style.So far in this Spring Boot series, we've explored important annotations such as @RequestParam, @PathVariable, and @Valid.

However, building APIs is not just about handling requests and responses. We also need to make sure that our APIs are secure and accessible only to authorized users.

In the next article, I'll cover Spring Security Basics, where we'll learn about Authentication, Authorization, and Security Configuration in Spring Boot applications with practical examples.


Comments

Popular posts from this blog

React Basics – How to Create Component

How to Build REST API using Spring Boot (Step-by-Step Guide)

Spring Boot @RequestParam Annotation Explained with Real-Time Examples