codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

Spring Boot

13 / 62 topics
11Creating RESTful Controllers12Request Mapping and HTTP Methods13Using Path Variables and Query Parameters14Using ResponseEntity for HTTP Responses
Tutorials/Spring Boot/Using Path Variables and Query Parameters
🍃Spring Boot

Using Path Variables and Query Parameters

Updated 2026-04-20
3 min read

Introduction

In web development, handling dynamic URLs is a common requirement. Spring Boot provides robust mechanisms for working with path variables and query parameters, enabling you to build flexible and responsive APIs. This tutorial will guide you through the process of using path variables and query parameters in your Spring Boot applications.

Understanding Path Variables

Path variables are parts of the URL that can be used to capture dynamic values. They are typically used to identify resources within a RESTful API. For example, in a URL like /users/{id}, {id} is a path variable that captures the user's ID.

Example: Using Path Variables

Let's create a simple Spring Boot application that uses path variables to retrieve user information.

  1. Create a new Spring Boot project using your preferred IDE or Spring Initializr. Choose dependencies such as "Spring Web".

  2. Define a User model:

package com.example.demo.model;

public class User {
    private Long id;
    private String name;

    // Constructors, getters, and setters
}
  1. Create a UserController to handle requests with path variables:
package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        // Simulate fetching user from a database
        return new User(id, "John Doe");
    }
}
  1. Run the application and test the endpoint:
curl http://localhost:8080/users/1

You should receive a response like:

{
  "id": 1,
  "name": "John Doe"
}

Best Practices for Path Variables

  • Use meaningful names: Choose variable names that clearly describe the data they represent.
  • Validate input: Always validate path variables to prevent invalid or malicious input.
  • Limit complexity: Avoid using too many path variables, as it can make URLs difficult to read and maintain.

Understanding Query Parameters

Query parameters are additional key-value pairs appended to a URL after a question mark (?). They are used to filter or sort data. For example, in a URL like /users?sort=name, sort is a query parameter that specifies sorting by name.

Example: Using Query Parameters

Let's extend our previous application to include query parameters for filtering users.

  1. Modify the UserController to handle query parameters:
package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

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

    @GetMapping
    public List<User> getUsers(@RequestParam(required = false, defaultValue = "id") String sort) {
        // Simulate fetching users from a database
        List<User> users = new ArrayList<>();
        users.add(new User(1L, "John Doe"));
        users.add(new User(2L, "Jane Smith"));

        // Sort logic (simplified)
        if ("name".equals(sort)) {
            users.sort((u1, u2) -> u1.getName().compareTo(u2.getName()));
        }

        return users;
    }
}
  1. Run the application and test the endpoint:
curl http://localhost:8080/users?sort=name

You should receive a response like:

[
  {
    "id": 1,
    "name": "Jane Smith"
  },
  {
    "id": 2,
    "name": "John Doe"
  }
]

Best Practices for Query Parameters

  • Use default values: Provide sensible default values for query parameters to avoid null checks.
  • Validate input: Validate query parameters to ensure they meet expected formats and constraints.
  • Document parameters: Clearly document the available query parameters, their meanings, and valid values.

Combining Path Variables and Query Parameters

In many cases, you might need to use both path variables and query parameters in a single endpoint. Let's extend our example to include both.

  1. Modify the UserController to handle both path variables and query parameters:
package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id, @RequestParam(required = false) String includeDetails) {
        // Simulate fetching user from a database
        User user = new User(id, "John Doe");

        // Include additional details logic (simplified)
        if ("true".equals(includeDetails)) {
            user.setName("John Doe - Detailed");
        }

        return user;
    }
}
  1. Run the application and test the endpoint:
curl http://localhost:8080/users/1?includeDetails=true

You should receive a response like:

{
  "id": 1,
  "name": "John Doe - Detailed"
}

Best Practices for Combining Path Variables and Query Parameters

  • Separate concerns: Use path variables for identifying resources and query parameters for filtering or modifying the request.
  • Maintain consistency: Ensure that the use of path variables and query parameters is consistent across your API.
  • Test thoroughly: Test endpoints with various combinations of path variables and query parameters to ensure they behave as expected.

Conclusion

Using path variables and query parameters effectively can significantly enhance the flexibility and usability of your Spring Boot applications. By following best practices, you can build robust APIs that are easy to use and maintain. This tutorial has provided a comprehensive guide on how to implement and utilize these features in your Spring Boot projects.


PreviousRequest Mapping and HTTP MethodsNext Using ResponseEntity for HTTP Responses

Recommended Gear

Request Mapping and HTTP MethodsUsing ResponseEntity for HTTP Responses