Definition
- @PathVariable binds a method parameter to a named segment in the URL path; in /accounts/{accountNumber}, the value SAV2001 is extracted and passed to the method.
- @RequestParam binds a method parameter to a query string parameter; in /accounts?status=ACTIVE, the value ACTIVE is extracted and passed to the method.
- Path segment is the part of the URL between slashes; it identifies a resource in REST conventions (e.g., /accounts/SAV2001/transactions/TXN001).
- Query string is the part of the URL after the question mark; it contains key-value pairs for filtering, sorting, and pagination (e.g., ?page=0&size=20&sort=date,desc).
- required is the attribute that controls whether the parameter is mandatory; @PathVariable is always required (missing path segments cause 404), while @RequestParam defaults to required but can be set to false.
- defaultValue is the attribute on @RequestParam that provides a fallback value when the parameter is not sent by the client.
Think of visiting a branch of National Bank of India. The branch number in the address (14th Cross Road, Branch 42) is like @PathVariable: it identifies which specific branch you are going to. When you arrive, you fill out a form asking what service you need, your preferred language, and whether you want an SMS receipt. These form fields are like @RequestParam: they modify how the branch serves you, but they do not change which branch you visit.
Understanding the Concepts
What is @PathVariable?
@PathVariable extracts a value from a segment of the URL path. In REST APIs, path variables identify specific resources. The URL pattern /accounts/{accountNumber} means the value between the last slash and the end of the path is the account number.
Spring matches the placeholder name in the URL mapping ({accountNumber}) to the method parameter name. If they match, you can omit the annotation value. If they differ, specify the name explicitly.
package com.bank.controller;
import com.bank.model.Account;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
// Path: /accounts/SAV2001
@GetMapping("/accounts/{accountNumber}")
public Account getAccount(@PathVariable String accountNumber) {
System.out.println("Path variable: accountNumber = " + accountNumber);
return accountService.getAccount(accountNumber);
}
// Multiple path variables: /accounts/SAV2001/transactions/TXN001
@GetMapping("/accounts/{accountNumber}/transactions/{txnId}")
public String getTransaction(
@PathVariable String accountNumber,
@PathVariable("txnId") String transactionId) {
System.out.println("accountNumber = " + accountNumber + ", txnId = " + transactionId);
return "Transaction " + transactionId + " for account " + accountNumber;
}
}
Expected output:
GET /accounts/SAV2001
Path variable: accountNumber = SAV2001
Response: {"accountNumber": "SAV2001", "holderName": "Priya Sharma", ...}
GET /accounts/SAV2001/transactions/TXN001
accountNumber = SAV2001, txnId = TXN001
Response: "Transaction TXN001 for account SAV2001"
What is @RequestParam?
@RequestParam extracts a value from the query string of the URL. Query parameters appear after the ? character and are separated by &. They are used for filtering, sorting, pagination, and other optional modifiers.
By default, @RequestParam is required. If the client does not send it, Spring returns 400 Bad Request. You can make it optional with required = false or provide a defaultValue.
package com.bank.controller;
import com.bank.model.Account;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class AccountSearchController {
private final AccountService accountService;
public AccountSearchController(AccountService accountService) {
this.accountService = accountService;
}
// GET /accounts?status=ACTIVE
@GetMapping("/accounts")
public List<Account> searchAccounts(
@RequestParam(required = false) String status,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
System.out.println("Query params: status=" + status + ", page=" + page + ", size=" + size);
return accountService.searchAccounts(status, page, size);
}
// GET /accounts/search?holderName=Priya&minBalance=10000
@GetMapping("/accounts/search")
public List<Account> advancedSearch(
@RequestParam(required = false) String holderName,
@RequestParam(required = false) java.math.BigDecimal minBalance,
@RequestParam(defaultValue = "balance,desc") String sort) {
System.out.println("Search: name=" + holderName + ", minBalance=" + minBalance + ", sort=" + sort);
return accountService.advancedSearch(holderName, minBalance, sort);
}
}
Expected output:
GET /accounts?status=ACTIVE
Query params: status=ACTIVE, page=0, size=20
Response: [{"accountNumber": "SAV2001", ...}, {"accountNumber": "SAV2002", ...}]
GET /accounts?status=ACTIVE&page=1&size=5
Query params: status=ACTIVE, page=1, size=5
GET /accounts (no params)
Query params: status=null, page=0, size=20
GET /accounts/search?holderName=Priya&minBalance=10000
Search: name=Priya, minBalance=10000, sort=balance,desc
What is the difference between @PathVariable and @RequestParam?
| Feature | @PathVariable | @RequestParam |
|---|---|---|
| Source | URL path segment (/accounts/{id}) | Query string (/accounts?id=1) |
| Purpose | Identify a specific resource | Filter, sort, paginate |
| Required | Always (missing = 404) | Configurable (default: required) |
| Default value | Not supported | Supported (defaultValue = "...") |
| REST convention | Resource identification | Query modifiers |
| Multiple values | Multiple path segments | Multiple query params |
| Encoding | URL path encoding | URL query encoding |
| Example | /accounts/SAV2001 | /accounts?status=ACTIVE |
package com.bank.controller;
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.RestController;
@RestController
public class ComparisonController {
// @PathVariable: identifies the account
// @RequestParam: modifies what data to return
@GetMapping("/accounts/{accountNumber}/transactions")
public String getTransactions(
@PathVariable String accountNumber,
@RequestParam(required = false) String fromDate,
@RequestParam(required = false) String toDate,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
System.out.println("Path: accountNumber = " + accountNumber);
System.out.println("Query: fromDate = " + fromDate);
System.out.println("Query: toDate = " + toDate);
System.out.println("Query: page = " + page + ", size = " + size);
return "Transactions for " + accountNumber
+ " from " + fromDate + " to " + toDate
+ " (page " + page + ", size " + size + ")";
}
}
Expected output:
GET /accounts/SAV2001/transactions?fromDate=2025-01-01&toDate=2025-06-30&page=0&size=10
Path: accountNumber = SAV2001
Query: fromDate = 2025-01-01
Query: toDate = 2025-06-30
Query: page = 0, size = 10
Response: "Transactions for SAV2001 from 2025-01-01 to 2025-06-30 (page 0, size 10)"
How do you validate @PathVariable and @RequestParam?
Spring supports Bean Validation annotations on path variables and request parameters. Add @Valid or individual constraint annotations like @Size, @Min, @Pattern. You also need @Validated on the controller class.
package com.bank.controller;
import com.bank.model.Account;
import com.bank.service.AccountService;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import org.springframework.validation.annotation.Validated;
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.RestController;
import java.util.List;
@RestController
@Validated
public class ValidatedAccountController {
private final AccountService accountService;
public ValidatedAccountController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/api/accounts/{accountNumber}")
public Account getAccount(
@PathVariable
@Pattern(regexp = "^(SAV|CUR)\\d{4}$", message = "Account number must be SAV or CUR followed by 4 digits")
String accountNumber) {
System.out.println("Validated account number: " + accountNumber);
return accountService.getAccount(accountNumber);
}
@GetMapping("/api/accounts")
public List<Account> listAccounts(
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "20") @Min(1) int size,
@RequestParam(required = false)
@Size(max = 50, message = "Holder name must be 50 characters or less")
String holderName) {
System.out.println("Validated: page=" + page + ", size=" + size + ", name=" + holderName);
return accountService.searchAccounts(holderName, page, size);
}
}
Expected output:
GET /api/accounts/SAV2001
Validated account number: SAV2001
Response: 200 OK
GET /api/accounts/INVALID
Response: 400 Bad Request
{"error": "Account number must be SAV or CUR followed by 4 digits"}
GET /api/accounts?page=-1
Response: 400 Bad Request
{"error": "page must be greater than or equal to 0"}
What is a complete banking project with @PathVariable and @RequestParam?
This project implements the National Bank of India account lookup REST API with both path variables and query parameters.
Project structure
account-api/
├── pom.xml
└── src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── bank/
│ │ ├── AccountApiApp.java
│ │ ├── controller/
│ │ │ └── AccountController.java
│ │ ├── dto/
│ │ │ └── AccountResponse.java
│ │ ├── model/
│ │ │ └── Account.java
│ │ ├── repository/
│ │ │ └── AccountRepository.java
│ │ └── service/
│ │ └── AccountService.java
│ └── resources/
│ └── application.properties
└── test/
└── java/
└── com/
└── bank/
└── controller/
└── AccountControllerTest.java
pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>account-apisyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-websyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-jpasyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-validationsyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>com.h2databasesyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>h2syn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
AccountResponse.java (Java 25 record)
package com.bank.dto;
import java.math.BigDecimal;
public record AccountResponse(
String accountNumber,
String holderName,
BigDecimal balance,
String status
) {}
AccountController.java
package com.bank.controller;
import com.bank.dto.AccountResponse;
import com.bank.service.AccountService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.List;
@RestController
@RequestMapping("/api/v1")
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
// @PathVariable: identify specific account
@GetMapping("/accounts/{accountNumber}")
public ResponseEntity<AccountResponse> getAccount(
@PathVariable String accountNumber) {
var account = accountService.getAccount(accountNumber);
return ResponseEntity.ok(account);
}
// @RequestParam: filter and paginate
@GetMapping("/accounts")
public ResponseEntity<List<AccountResponse>> listAccounts(
@RequestParam(required = false) String status,
@RequestParam(required = false) BigDecimal minBalance,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
var accounts = accountService.searchAccounts(status, minBalance, page, size);
return ResponseEntity.ok(accounts);
}
// Both together: path identifies resource, query modifies behavior
@GetMapping("/accounts/{accountNumber}/statement")
public ResponseEntity<String> getStatement(
@PathVariable String accountNumber,
@RequestParam(defaultValue = "2025-01-01") String fromDate,
@RequestParam(defaultValue = "2025-12-31") String toDate,
@RequestParam(defaultValue = "PDF") String format) {
var statement = accountService.generateStatement(
accountNumber, fromDate, toDate, format);
return ResponseEntity.ok(statement);
}
// @PathVariable for DELETE: identify what to delete
@DeleteMapping("/accounts/{accountNumber}")
public ResponseEntity<Void> closeAccount(@PathVariable String accountNumber) {
accountService.closeAccount(accountNumber);
return ResponseEntity.noContent().build();
}
}
AccountControllerTest.java
package com.bank.controller;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import java.math.BigDecimal;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class AccountControllerTest {
@Autowired private MockMvc mockMvc;
@Autowired private AccountRepository accountRepository;
@BeforeEach
void setUp() {
accountRepository.deleteAll();
accountRepository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("50000"), "ACTIVE"));
accountRepository.save(new Account("SAV2002", "Rajesh Kumar", new BigDecimal("150000"), "ACTIVE"));
accountRepository.save(new Account("CUR3001", "Amit Patel", new BigDecimal("300000"), "CLOSED"));
}
@Test
void getAccount_pathVariable() throws Exception {
mockMvc.perform(get("/api/v1/accounts/SAV2001"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accountNumber").value("SAV2001"))
.andExpect(jsonPath("$.holderName").value("Priya Sharma"));
System.out.println("PASS: @PathVariable extracted SAV2001 from URL path");
}
@Test
void listAccounts_requestParam() throws Exception {
mockMvc.perform(get("/api/v1/accounts")
.param("status", "ACTIVE")
.param("page", "0")
.param("size", "10"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(2));
System.out.println("PASS: @RequestParam filtered 2 ACTIVE accounts");
}
@Test
void getStatement_bothAnnotations() throws Exception {
mockMvc.perform(get("/api/v1/accounts/SAV2001/statement")
.param("fromDate", "2025-01-01")
.param("toDate", "2025-06-30")
.param("format", "CSV"))
.andExpect(status().isOk());
System.out.println("PASS: @PathVariable + @RequestParam used together");
}
}
Expected output:
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
PASS: @PathVariable extracted SAV2001 from URL path
PASS: @RequestParam filtered 2 ACTIVE accounts
PASS: @PathVariable + @RequestParam used together
[INFO] BUILD SUCCESS
What are common mistakes with @PathVariable and @RequestParam?
Wrong: using @RequestParam for resource identification
package com.bank.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WrongResourceIdentification {
// WRONG: using query param to identify a specific account
// GET /accounts?accountNumber=SAV2001
@GetMapping("/wrong/accounts")
public String getAccount(@RequestParam String accountNumber) {
System.out.println("WRONG: /accounts?accountNumber=" + accountNumber);
System.out.println(" This is not RESTful.");
System.out.println(" Resource identification belongs in the path.");
return "Account: " + accountNumber;
}
}
Expected output:
WRONG: /accounts?accountNumber=SAV2001
This is not RESTful.
Resource identification belongs in the path.
Correct: use @PathVariable for resource identification
package com.bank.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CorrectResourceIdentification {
// CORRECT: account number in the path
// GET /accounts/SAV2001
@GetMapping("/correct/accounts/{accountNumber}")
public String getAccount(@PathVariable String accountNumber) {
System.out.println("CORRECT: /accounts/" + accountNumber);
System.out.println(" RESTful: resource identified by path.");
return "Account: " + accountNumber;
}
}
Expected output:
CORRECT: /accounts/SAV2001
RESTful: resource identified by path.
What should a senior or principal engineer know?
At the senior level, you should design URL structures that follow REST conventions: nouns for resources, path variables for identification, query parameters for filtering. The URL should be readable: GET /api/v1/accounts/SAV2001/transactions?type=DEBIT&fromDate=2025-01-01.
At the principal level, think about:
- URL versioning: use path-based versioning (/api/v1/accounts, /api/v2/accounts) for major breaking changes. Query parameter or header versioning are alternatives.
- Pagination contract: standardize pagination across all endpoints. Use page/size for offset pagination, or cursor-based for large datasets.
- Security of path variables: never pass sensitive data (passwords, tokens, SSN) in path variables or query parameters. They appear in access logs, browser history, and referrer headers.
- Type conversion: Spring automatically converts path variables and query parameters to the method parameter type (String, int, Long, BigDecimal, LocalDate, enums). Register custom converters for domain types.
package com.bank.controller;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
// Custom converter: String query param -> LocalDate
@Component
public class StringToLocalDateConverter implements Converter<String, LocalDate> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Override
public LocalDate convert(String source) {
System.out.println("Converting query param '" + source + "' to LocalDate");
return LocalDate.parse(source, FORMATTER);
}
}
package com.bank.controller;
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.RestController;
import java.time.LocalDate;
@RestController
public class TypeConversionController {
@GetMapping("/api/v1/accounts/{accountNumber}/transactions")
public String getTransactions(
@PathVariable String accountNumber,
@RequestParam LocalDate fromDate,
@RequestParam LocalDate toDate) {
System.out.println("accountNumber: " + accountNumber);
System.out.println("fromDate: " + fromDate + " (type: " + fromDate.getClass().getSimpleName() + ")");
System.out.println("toDate: " + toDate + " (type: " + toDate.getClass().getSimpleName() + ")");
return "Transactions from " + fromDate + " to " + toDate;
}
}
Expected output:
GET /api/v1/accounts/SAV2001/transactions?fromDate=2025-01-01&toDate=2025-06-30
Converting query param '2025-01-01' to LocalDate
Converting query param '2025-06-30' to LocalDate
accountNumber: SAV2001
fromDate: 2025-01-01 (type: LocalDate)
toDate: 2025-06-30 (type: LocalDate)
What are common interview follow-up questions?
- Can @PathVariable be optional? (In Spring Boot 3.x, you can use Optional
or set required = false with a default method parameter. But a missing path segment usually results in a different URL pattern, so this is rare.) - What happens if the path variable contains a slash? (By default, Spring treats slashes as path separators. The value is truncated at the slash. Use a regex pattern like {filename:.+} to match slashes.)
- Can @RequestParam accept a list? (Yes. /accounts?status=ACTIVE&status=CLOSED maps to @RequestParam List
status. Spring collects all values for the same parameter name.) - What is the difference between @RequestParam and @RequestBody? (@RequestParam reads from the query string. @RequestBody reads the entire HTTP body and deserializes it, typically JSON for POST/PUT requests.)
- Should you use @PathVariable for filtering? (No. Filtering is a query modifier, not a resource identifier. Use query parameters for filtering.)
- How does Spring handle URL encoding in path variables? (Spring automatically decodes URL-encoded characters. %20 becomes a space, %2F becomes a slash.)
Visual Overview
URL Anatomy: @PathVariable vs @RequestParam
==============================================
GET /api/v1/accounts/SAV2001/transactions?type=DEBIT&fromDate=2025-01-01&page=0&size=20
├──────┤ ├────┤ ├──────┤ ├───────────┤ ├────────────────────────────────────────────┤
scheme ver resource path variable query string (@RequestParam)
(@PathVariable)
Mapping:
@GetMapping("/api/v1/accounts/{accountNumber}/transactions")
public List<Transaction> get(
@PathVariable String accountNumber, <-- SAV2001
@RequestParam String type, <-- DEBIT
@RequestParam String fromDate, <-- 2025-01-01
@RequestParam int page, <-- 0
@RequestParam int size <-- 20
)
REST URL Design Convention
===========================
GET /accounts List all (+ @RequestParam for filters)
GET /accounts/{id} Get one (@PathVariable)
POST /accounts Create (@RequestBody)
PUT /accounts/{id} Update (@PathVariable + @RequestBody)
DELETE /accounts/{id} Delete (@PathVariable)
GET /accounts/{id}/transactions Sub-resource (@PathVariable + @RequestParam)
Key Takeaway
@PathVariable and @RequestParam are the two primary ways to accept input from a URL in Spring Boot REST controllers. @PathVariable extracts values from the URL path (/accounts/SAV2001) and is used for resource identification. @RequestParam extracts values from the query string (/accounts?status=ACTIVE) and is used for filtering, sorting, and pagination.
The key rule is: use @PathVariable when the value identifies what resource you are accessing, and use @RequestParam when the value modifies how you access it. In our National Bank of India account-api, GET /api/v1/accounts/SAV2001 uses @PathVariable to identify the account, while GET /api/v1/accounts?status=ACTIVE&page=0&size=20 uses @RequestParam to filter and paginate the list.
Both annotations support type conversion (Spring converts strings to int, BigDecimal, LocalDate, enums automatically) and validation (with @Pattern, @Min, @Size and @Validated on the controller). They can be combined in the same method: GET /accounts/{accountNumber}/transactions?fromDate=2025-01-01&toDate=2025-06-30 uses @PathVariable for the account and @RequestParam for the date range.
At the senior level, design clean REST URLs with nouns for resources and consistent pagination. At the principal level, standardize URL versioning across the API, implement custom converters for domain types, and never pass sensitive data in URLs.
Remember one sentence: @PathVariable identifies which resource (the noun in the URL path), and @RequestParam modifies how you interact with it (the filters in the query string).
---