LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1319 min read

Path Variables & Request Parameters

Learn how to extract data from the URL path with @PathVariable and from query strings with @RequestParam, including defaults and required flags.

Introduction

Most real endpoints need more than a fixed URL — they need to know which resource you're asking about, or how you want the results filtered. Spring Boot gives you two annotations for pulling that information out of an incoming request: @PathVariable for values embedded in the URL path itself, and @RequestParam for values passed as query string parameters. This lesson covers both in depth.

What You Will Learn
  • How @PathVariable binds a URL segment to a method parameter.
  • How to read multiple path variables from one URL.
  • How @RequestParam reads query string values.
  • How to set default values and mark parameters as optional.

@PathVariable

A path variable is a placeholder inside the URL template, written in curly braces. Spring extracts the matching segment from the actual request URL and passes it to your method as a typed argument.

@RestController
@RequestMapping("/api/students")
public class StudentController {
@GetMapping("/{id}")
public String getStudent(@PathVariable Long id) {
return "Fetching student with id: " + id;
}
}
Example Request

Click Run to see what this code prints.

By default, Spring matches the {id} placeholder to a parameter named id. If you want the parameter name to differ from the placeholder, specify it explicitly with @PathVariable("id").

@GetMapping("/{studentId}")
public String getStudent(@PathVariable("studentId") Long id) {
return "Fetching student with id: " + id;
}

Multiple Path Variables

A URL can contain more than one placeholder, which is common when a resource is nested inside another, such as a course's specific enrolled student.

@GetMapping("/courses/{courseId}/students/{studentId}")
public String getEnrollment(@PathVariable Long courseId, @PathVariable Long studentId) {
return "Course " + courseId + ", Student " + studentId;
}
Example Request

Click Run to see what this code prints.

@RequestParam

Query string parameters — the key=value pairs after a ? in a URL — are read with @RequestParam. These are typically used for filtering, sorting, pagination, and optional search criteria, rather than identifying a specific resource.

@GetMapping("/search")
public String search(@RequestParam String name) {
return "Searching for students named: " + name;
}
Example Request

Click Run to see what this code prints.

Defaults and Optional Parameters

By default, @RequestParam is required — if the request omits it, Spring returns a 400 Bad Request before your method even runs. You can make a parameter optional with required = false, and give it a fallback value with defaultValue.

@GetMapping("/search")
public String search(
@RequestParam(required = false) String name,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return "name=" + name + ", page=" + page + ", size=" + size;
}
Example Requests

Click Run to see what this code prints.

defaultValue Implies required = false

You don't need to combine required = false with defaultValue — setting a defaultValue automatically makes the parameter optional, since Spring always has a fallback to use.

Common Mistakes

Avoid These Mistakes
  • Mixing up @PathVariable and @RequestParam — path variables identify a resource (/students/42), request parameters filter or modify a request (?page=2).
  • Forgetting required = false on an optional @RequestParam, causing a 400 error whenever the client omits it.
  • Using a primitive type like int for an optional parameter without a defaultValue, since null cannot be assigned to a primitive.
  • Not naming @PathVariable explicitly when compiling without the -parameters flag, which can break name matching in older setups.

Best Practices

  • Use @PathVariable for anything that identifies a specific resource, and @RequestParam for filtering, sorting, or paging.
  • Give pagination parameters sensible defaults (defaultValue = "0" for page, a reasonable size) so clients rarely need to pass them.
  • Use wrapper types like Integer instead of int for optional numeric parameters so you can safely check for null.
  • Validate path variables and request parameters before using them in database lookups to avoid unnecessary errors deep in your code.

Frequently Asked Questions

Spring Boot returns a 400 Bad Request automatically, before your controller method runs, along with a message naming the missing parameter.

Yes. Spring will bind it to whatever type you declare, including String. Using a specific type like Long or Integer gives you automatic validation, since a non-numeric value causes a 400 error instead of reaching your business logic.

Yes, using a List<String> or similar collection type, which Spring populates from repeated parameters like ?tag=java&tag=spring.

No hard limit imposed by Spring, but readability suffers past two or three path variables — that usually signals the URL structure needs rethinking.

Key Takeaways

  • @PathVariable extracts values embedded directly in the URL path, typically resource identifiers.
  • @RequestParam extracts query string values, typically used for filtering and pagination.
  • required = false makes a parameter optional; defaultValue supplies a fallback and implies optional.
  • Choosing the right annotation for the right kind of data keeps your URLs clean and RESTful.

Summary

You can now read data from both the URL path and the query string, with sensible defaults for optional values. Next, you'll learn how to accept a full JSON object as input with @RequestBody, and how to control the exact HTTP status code your API returns with ResponseEntity.

Next Lesson →

Request Body & ResponseEntity