Skip to content
intermediatePhase ·

Path Variables

Use @PathVariable to extract values from URL paths.

25m
0 problems
Topic Progress0%

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

  1. Follow SOLID principles
  2. Write clean, readable code
  3. Test thoroughly
  4. Document decisions
  5. 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

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0/3solved
Implement Path Variables

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
}
Path Variables Edge Cases

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, idempotency
Path Variables Testing Strategy

Write 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 injection

Quiz

1. When should you use @PathVariable over @RequestParam?

Question 1 options

2. How do you restrict a path variable to digits only?

Question 2 options

3. What is the primary purpose of Path Variables?

Question 3 options

4. What is a common mistake when implementing Path Variables?

Question 4 options

Flashcards

Question

@PathVariable use case?

Answer

Identify specific resources in URL path (/products/{id})

Question

PathVariable vs RequestParam?

Answer

PathVariable = path segments, RequestParam = query strings

Question

What is Path Variables?

Answer

Path Variables is a key concept in backend development.

Question

When to use Path Variables?

Answer

Use Path Variables when building production systems that require reliability, scalability, and maintainability.

Question

Path Variables best practices

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