Path Variables
@PathVariable
@GetMapping("/products/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
return productService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
Multiple Path Variables
@GetMapping("/users/{userId}/orders/{orderId}")
public ResponseEntity<Order> getUserOrder(
@PathVariable Long userId,
@PathVariable Long orderId) {
return ResponseEntity.ok(orderService.getUserOrder(userId, orderId));
}
Path Variable with Regex
@GetMapping("/products/{id:\\d+}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
// Only matches numeric IDs
}
@GetMapping("/files/{filename:[a-zA-Z0-9]+}")
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
// Only matches alphanumeric filenames
}
Path Variable vs Query Parameter
| Use Case | Path Variable | Query Parameter |
|---|---|---|
| Resource identification | /products/123 |
?id=123 |
| Filtering | Not suitable | ?category=phone |
| Hierarchical resources | /users/123/orders |
Not suitable |
| Required identification | Preferred | Alternative |
Best Practices
Key Principles
- Follow SOLID principles
- Write clean, readable code
- Test thoroughly
- Document decisions
- Monitor in production
Implementation
- Start simple, refactor as needed
- Use established patterns
- Consider trade-offs
- Review with peers
Continuous Improvement
- Learn from incidents
- Update documentation
- Share knowledge
- Mentor others
Key Points
- Understanding Path Variables is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Path Variables in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Path Variables implementation
// Key aspects: validation, error handling, logging, testing
public class PathVariables {
// Production-ready implementation
}Identify and handle edge cases for Path Variables. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Path Variables. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. When should you use @PathVariable over @RequestParam?
2. How do you restrict a path variable to digits only?
3. What is the primary purpose of Path Variables?
4. What is a common mistake when implementing Path Variables?
Flashcards
Question
@PathVariable use case?
Click to reveal answer
Answer
Identify specific resources in URL path (/products/{id})
Question
PathVariable vs RequestParam?
Click to reveal answer
Answer
PathVariable = path segments, RequestParam = query strings
Question
What is Path Variables?
Click to reveal answer
Answer
Path Variables is a key concept in backend development.
Question
When to use Path Variables?
Click to reveal answer
Answer
Use Path Variables when building production systems that require reliability, scalability, and maintainability.
Question
Path Variables best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.@PathVariable extracts values from URL path segments
- 2.Use for resource identification: /products/{id}
- 3.Regex can restrict path variable format
- 4.Use path variables for hierarchy, query params for filtering
Interview Tips
- •Know when to use path variables vs query params
- •Handle path variable validation
Cheat Sheet
Path Variables
- @PathVariable: URL path segments (/products/{id})
- Multiple: /users/{userId}/orders/{orderId}
- Regex: {id:\d+} (digits only)
- Use: Resource identification, hierarchical URLs