GET Mapping and PathVariable
Browsers love GET. APIs love @PathVariable.
The Hyderabad Parcel Delivery Analogy:
Imagine you go to the DTDC courier office in Hyderabad to collect a parcel. You don't just walk up to the counter and say: "Give me my parcel." The clerk will ask: "Which parcel? What is the tracking number?" You reply: "Tracking number is 404."
A @PathVariable in a URL is exactly like this tracking number. You send a specific ID in the URL (e.g., /books/404), and Spring extracts the 404 from the URL structure and drops it directly into your Java method's variable (int id).
- @GetMapping("/path/{id}"): This tells Spring that this method will handle HTTP GET requests. The
{id}part is a placeholder (a URI template variable) inside the URL path. - @PathVariable int id: This annotation tells Spring: "Look at the URL path, find the part that matched
{id}, pull it out, and assign it to thisint idvariable." (The variable name must match exactly, or you must write@PathVariable("id")).
package com.devinhyderabad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
// 1. REST Controller to handle web requests
@RestController
@RequestMapping("/api/books")
class BookController {
// Simulating a database with an in-memory list
private List books = new ArrayList<>(List.of(
new Book(101, "Hyderabad History", "Sai"),
new Book(102, "Spring Boot Guide", "Deva")
));
// 2. Maps GET requests like /api/books/101
@GetMapping("/{id}")
public Book getBookById(@PathVariable int id) {
// 3. Spring extracts '101' from URL and puts it in 'id'
for (Book book : books) {
if (book.getId() == id) {
return book; // Spring converts this to JSON
}
}
return null; // If not found
}
}
// Simple Data Class
class Book {
private int id;
private String title;
private String author;
public Book(int id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
// Getters are REQUIRED for JSON conversion
public int getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
} If you run this and go to http://localhost:8080/api/books/101 in your browser or Postman, you will get: {"id":101,"title":"Hyderabad History","author":"Sai"}.
Interview Question: "What happens if the URL path variable name and the method parameter name don't match?"
Answer: If the URL is /{bookId} and the Java parameter is int id, Spring will throw an error because it cannot find a matching name. To fix this, you must explicitly map it using @PathVariable("bookId") int id.
Enterprise Note: In real enterprise apps, you rarely return null when an item isn't found. As we will see in the status code chapter, you should return a 404 Not Found HTTP status. Returning null gives the client a 200 OK with an empty body, which is misleading.
Key Takeaways
- ✅ @GetMapping handles HTTP GET requests
- ✅ @PathVariable extracts values from URL templates like /{id}
- ✅ Path variable name must match method parameter name (or use explicit name)
- ✅ Browsers can directly test GET endpoints — no Postman needed
Want to track your progress?
Log in to save your place and pick up where you left off.
Progress track karna chahte ho?
Login karo apni progress save karne ke liye aur jahan chhoda tha wahan se shuru karo.
Login