DEV Community

Er. Bhupendra
Er. Bhupendra

Posted on

ALL TYPE OF GET USES IN SPRING BOOT

Industry standards mein GET mapping ko handle karne ke kaafi tareeqe hote hain. Aapne jo /{vendorId} wala likha hai, wo sirf ek basic example hai.

Industry mein use hone waale top 5 patterns ye rahe, jinhe aapko practice karna chahiye:

1. Get All (Saara data fetch karne ke liye)

Jab aapko list of items chahiye hoti hai, tab hum bina kisi ID ke GET call karte hain.

  • URL: /cloudvendor
  • Method:
@GetMapping
public List<CloudVendor> getAllCloudVendorDetails() {
    return List.of(
        new CloudVendor("C1", "Amazon", "USA", "1234"),
        new CloudVendor("C2", "Google", "USA", "5678")
    );
}
Enter fullscreen mode Exit fullscreen mode

2. Get by PathVariable (Jo aapne likha hai - Specific ID ke liye)

Ye tab use hota hai jab resource unique ho.

  • URL: /cloudvendor/C1
  • Method: (Aapka method sahi hai, bas professional coding mein hum ResponseEntity use karte hain status codes ke liye).
@GetMapping("/{vendorId}")
public ResponseEntity<CloudVendor> getCloudVendorDetails(@PathVariable String vendorId) {
    CloudVendor vendor = new CloudVendor(vendorId, "Vendor 1", "Address One", "xxxx");
    return ResponseEntity.ok(vendor); // 200 OK status ke saath return karega
}
Enter fullscreen mode Exit fullscreen mode

3. Filtering using Query Parameters (@RequestParam)

Industry mein sabse zyada use hone wala pattern. Jab humein filter lagana ho (e.g., city ke basis pe search karna).

  • URL: /cloudvendor?city=Mumbai
  • Method:
@GetMapping("/search")
public List<CloudVendor> getVendorsByCity(@RequestParam(name = "city") String city) {
    // Logic to filter vendors by city
    return someList;
}
Enter fullscreen mode Exit fullscreen mode

Tip: Isme required = false ya defaultValue bhi de sakte ho.

4. Pagination and Sorting (Large Data ke liye)

Jab data bahut zyada hota hai (hazaron mein), tab saara data ek baar mein nahi bhejte.

  • URL: /cloudvendor/all?page=0&size=10&sort=name
  • Method:
@GetMapping("/all")
public List<CloudVendor> getVendorsPaged(
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size,
        @RequestParam(defaultValue = "vendorName") String sortBy) {
    // Service layer call with pageable
    return service.getVendors(page, size, sortBy);
}
Enter fullscreen mode Exit fullscreen mode

5. Nested Resources (Relationship ke liye)

Jab ek vendor ke andar ki cheezein chahiye ho. Maan lijiye ek Vendor ke multiple Service Plans hain.

  • URL: /cloudvendor/{vendorId}/services
  • Method:
@GetMapping("/{vendorId}/services")
public List<ServicePlan> getVendorServices(@PathVariable String vendorId) {
    // Specific vendor ki services list return karega
    return service.getServicesByVendor(vendorId);
}
Enter fullscreen mode Exit fullscreen mode

Inhe Practice kaise karein? (Summary Table)

Target Mapping URL Annotation Example
All Records /cloudvendor @GetMapping Get list of all vendors
Specific Record /cloudvendor/{id} @PathVariable Get Vendor by ID (Unique)
Search/Filter /cloudvendor?name=AWS @RequestParam Search vendors by name
Pagination /cloudvendor?page=1 @RequestParam Get 2nd page of results
Relationship /cloudvendor/{id}/bill @PathVariable Get bills of a specific vendor

Industry me Best Practice: ResponseEntity use karna

Professional projects mein hum direct object return nahi karte, balki ResponseEntity<?> return karte hain taaki hum HTTP Status Codes (200, 404, 500) control kar sakein.

Example:

@GetMapping("/{vendorId}")
public ResponseEntity<Object> getCloudVendorDetails(@PathVariable String vendorId) {
    if(vendorId.equals("notfound")) {
        return new ResponseEntity<>("Vendor Not Found", HttpStatus.NOT_FOUND); // 404
    }
    return new ResponseEntity<>(new CloudVendor(vendorId, "AWS", "USA", "11"), HttpStatus.OK); // 200
}
Enter fullscreen mode Exit fullscreen mode

In 5 patterns ki practice kar lijiye, GET request handle karne ka 90% kaam isi se hota hai.

2ND

Industry-level Spring Boot me GET endpoints ko usually 6–10 common patterns me likha/handle kiya jaata hai. Tum practice ke liye in sab ko implement kar sakte ho. Niche examples CloudVendor domain ke hisaab se diye hain.

(Reference: Spring MVC annotation method docs / @GetMapping, @PathVariable, @RequestParam, etc. Spring Ref, @GetMapping javadoc)


1) Single resource by id

GET /cloudvendors/{id} → ek vendor

@RestController
@RequestMapping("/cloudvendors")
public class CloudVendorController {

  private final CloudVendorService service;

  public CloudVendorController(CloudVendorService service) {
    this.service = service;
  }

  @GetMapping("/{vendorId}")
  public ResponseEntity<CloudVendor> getById(@PathVariable String vendorId) {
    return service.getById(vendorId)
        .map(ResponseEntity::ok)
        .orElseGet(() -> ResponseEntity.notFound().build());
  }
}
Enter fullscreen mode Exit fullscreen mode

Industry me aksar ResponseEntity use hota hai taaki 404/200 cleanly return ho. (ResponseEntity)


2) Collection endpoint (list all)

GET /cloudvendors → saare vendors

@GetMapping
public List<CloudVendor> getAll() {
  return service.getAll();
}
Enter fullscreen mode Exit fullscreen mode

3) Filtering via query params

GET /cloudvendors?name=aws

GET /cloudvendors?city=delhi&status=ACTIVE

@GetMapping(params = "name")
public List<CloudVendor> findByName(@RequestParam String name) {
  return service.findByName(name);
}

@GetMapping(params = {"city", "status"})
public List<CloudVendor> findByCityAndStatus(
    @RequestParam String city,
    @RequestParam String status
) {
  return service.findByCityAndStatus(city, status);
}
Enter fullscreen mode Exit fullscreen mode

Tip: @GetMapping(params="...") se same path /cloudvendors par different GET handlers cleanly separate ho jaate hain.

(@RequestParam)


4) Search endpoint (separate path)

Kabhi-kabhi teams filter ko /search me rakhte hain (personal/team convention).

GET /cloudvendors/search?query=ven

@GetMapping("/search")
public List<CloudVendor> search(@RequestParam String query) {
  return service.search(query);
}
Enter fullscreen mode Exit fullscreen mode

5) Pagination + sorting (industry standard)

GET /cloudvendors?page=0&size=20&sort=name,asc

Agar tum Spring Data use kar rahe ho, to Pageable best practice hai:

@GetMapping
public Page<CloudVendor> getAllPaged(Pageable pageable) {
  return service.getAllPaged(pageable);
}
Enter fullscreen mode Exit fullscreen mode

page/size/sort style common hai (Spring Data conventions). (Pageable: https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Pageable.html)

Agar Spring Data nahi bhi ho, manually handle kar sakte ho:

@GetMapping
public List<CloudVendor> getAllManual(
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "20") int size
) {
  return service.getAllManual(page, size);
}
Enter fullscreen mode Exit fullscreen mode

6) Nested resources (sub-resource)

Example: vendor ke “products” ya “regions”:

GET /cloudvendors/{id}/regions

@GetMapping("/{vendorId}/regions")
public List<String> getRegions(@PathVariable String vendorId) {
  return service.getRegions(vendorId);
}
Enter fullscreen mode Exit fullscreen mode

7) Returning DTO (not entity) + stable API contracts

Industry me direct model/entity return karne ke bajay aksar DTO return hota hai.

public record CloudVendorResponse(String id, String name, String address) {}

@GetMapping("/{vendorId}")
public ResponseEntity<CloudVendorResponse> getByIdDto(@PathVariable String vendorId) {
  return service.getById(vendorId)
      .map(v -> ResponseEntity.ok(new CloudVendorResponse(v.getVendorId(), v.getVendorName(), v.getVendorAddress())))
      .orElseGet(() -> ResponseEntity.notFound().build());
}
Enter fullscreen mode Exit fullscreen mode

8) Content negotiation / produces

Agar sirf JSON support karna hai:

@GetMapping(value = "/{vendorId}", produces = "application/json")
public CloudVendor getJson(@PathVariable String vendorId) {
  return service.mustGet(vendorId);
}
Enter fullscreen mode Exit fullscreen mode

(produces on mapping)


9) Proper error handling (404/400) via exception + global handler

Controller me baar-baar 404 return na karna ho to:

@GetMapping("/{vendorId}")
public CloudVendor getByIdOrThrow(@PathVariable String vendorId) {
  return service.getById(vendorId)
      .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Vendor not found"));
}
Enter fullscreen mode Exit fullscreen mode

(ResponseStatusException)

Aur global handler:

@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(ResponseStatusException.class)
  public ResponseEntity<Map<String, Object>> handle(ResponseStatusException ex) {
    Map<String, Object> body = Map.of(
        "status", ex.getStatusCode().value(),
        "message", ex.getReason()
    );
    return ResponseEntity.status(ex.getStatusCode()).body(body);
  }
}
Enter fullscreen mode Exit fullscreen mode

(@RestControllerAdvice)


10) Conditional GET (ETag / caching) — advanced but real-world

High-traffic APIs me caching help karti hai. (Implementation team-specific hota hai; Spring me support hai.)

Idea: If-None-Match header ke basis par 304 Not Modified return. (This is more advanced; practice later.)


Practice checklist (tumhare current code se next steps)

  1. /cloudvendors list endpoint
  2. /cloudvendors/{id} with ResponseEntity + 404
  3. /cloudvendors?name=... filter
  4. /cloudvendors/search?query=...
  5. Pagination: /cloudvendors?page=&size=&sort=
  6. /cloudvendors/{id}/regions nested
  7. DTO return
  8. Global exception handling

Agar tum chaho to main tumhare existing CloudVendor model + in-memory list (fake DB) ke saath complete working controller/service ka code ek saath de sakta hoon, jisme ye saare GET patterns runnable ho jaayen.

Top comments (0)