Skip to lesson

@PathVariable and @RequestParam

A shopper filters phones under a price, opens page two of the list and then taps one product. The URL must tell the server which product, and how to filter the list.

@PathVariable for /api/v1/products/{id}

A path variable is a {placeholder} part of the URL path, read with @PathVariable. With @GetMapping("/{id}"), the request GET /api/v1/products/3 calls the method with id = 3.

A product page needs the id from the URL, the 3 in /api/v1/products/3. The example reads two ids from a nested address URL.

Example 1 · Address.java, AddressController.java: two path variables

Runs in: the rest-lab practice project (Spring Boot 4.1)

Address.javaJava
package com.shoplite.lab.customer;
public record Address(long id, long customerId, String label, String line1, String city,                      String state, String pincode, boolean isDefault) {}
package com.shoplite.lab.customer;
import java.util.List;
import org.springframework.http.ResponseEntity;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;
@RestController@RequestMapping("/api/v1/customers/{customerId}/addresses")public class AddressController {
    // Three seed addresses, fixed for this example    private static final List<Address> ADDRESSES = List.of(            new Address(1, 1, "Home", "12 MG Road, Indiranagar", "Bengaluru", "Karnataka", "560038", true),            new Address(2, 1, "Work", "Prestige Tech Park, Marathahalli", "Bengaluru", "Karnataka", "560103", false),            new Address(3, 2, "Home", "7 Anna Salai, T Nagar", "Chennai", "Tamil Nadu", "600017", true));
    @GetMapping("/{addressId}")    public ResponseEntity<Address> get(@PathVariable long customerId, @PathVariable("addressId") long id) {        return ResponseEntity.of(ADDRESSES.stream()                .filter(a -> a.id() == id && a.customerId() == customerId)   // must be this customer's                .findFirst());    }}
Sample output
$ curl http://localhost:8080/api/v1/products/3
{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true}
$ curl http://localhost:8080/api/v1/customers/1/addresses/2
{"id":2,"customerId":1,"label":"Work","line1":"Prestige Tech Park, Marathahalli","city":"Bengaluru","state":"Karnataka","pincode":"560103","isDefault":false}
$ curl -i http://localhost:8080/api/v1/customers/2/addresses/1
HTTP/1.1 404
Content-Length: 0
Date: Fri, 16 Oct 2026 04:58:16 GMT

What this code does

  • The first call uses the product controller's @GetMapping("/{id}") with @PathVariable long id: 3 in the URL becomes id = 3.
  • {customerId} sits in the class base path and {addressId} in the method path. @PathVariable("addressId") long id shows how to give the Java parameter a different name.
  • Address 1 exists but belongs to customer 1, so customer 2 gets 404: the filter checks both ids. The address list is fixed in the controller only to keep this example short.

The parameter name must match the placeholder, or you name it: @PathVariable("addressId") long id. A path can hold several variables, and the class base path can hold them too. @RequestMapping("/api/v1/customers/{customerId}/addresses") plus @GetMapping("/{addressId}") reads both ids from /api/v1/customers/1/addresses/2.

Nested URLs need a check that the child really belongs to the parent. Address 1 exists, but it is customer 1's, so /customers/2/addresses/1 must answer 404, never someone else's address.

Spring reads parameter names from the compiled class. The Spring Boot parent compiles with -parameters, so @PathVariable long id just works. Without it, startup is fine but the first request fails with Name for argument of type [long] not specified.

@RequestParam: required, defaultValue and Optional

A query parameter is a name=value pair after the ? in a URL, read with @RequestParam. By default it is required: if it is missing, Spring answers 400 before your method runs.

The product list must accept page and size, and use sensible values when the client sends none. The example adds @RequestParam with defaults to the list method.

Example 2 · PageResponse.java and the list method in ProductController.java

Runs in: the rest-lab practice project (Spring Boot 4.1)

PageResponse.javaJava
package com.shoplite.lab.common;
import java.util.List;
public record PageResponse<T>(List<T> content, int page, int size, long totalElements, int totalPages) {
    public static <T> PageResponse<T> of(List<T> all, int page, int size) {        int from = (int) Math.min((long) page * size, all.size());        int to = Math.min(from + size, all.size());        int totalPages = (all.size() + size - 1) / size;        return new PageResponse<>(all.subList(from, to), page, size, all.size(), totalPages);    }}
package com.shoplite.lab.product;
import java.math.BigDecimal;import java.util.List;import java.util.Optional;
import com.shoplite.lab.common.PageResponse;
import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;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.PatchMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping(path = "/api/v1/products", produces = MediaType.APPLICATION_JSON_VALUE)public class ProductController {
    private final ProductService productService;
    public ProductController(ProductService productService) {        this.productService = productService;    }
    @GetMapping    public PageResponse<Product> list(            @RequestParam(required = false) Long categoryId,            @RequestParam Optional<BigDecimal> minPrice,            @RequestParam Optional<BigDecimal> maxPrice,            @RequestParam(defaultValue = "false") boolean includeInactive,            @RequestParam(defaultValue = "0") int page,            @RequestParam(defaultValue = "20") int size) {        List<Product> matches = productService.search(categoryId, minPrice.orElse(null),                maxPrice.orElse(null), includeInactive);        return PageResponse.of(matches, page, size);    }
    @GetMapping("/{id}")    public ResponseEntity<Product> get(@PathVariable long id) {        return ResponseEntity.of(productService.findById(id));    }
    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)    @ResponseStatus(HttpStatus.CREATED)    public Product create(@RequestBody CreateProductRequest request) {        return productService.create(request);    }
    @PutMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)    public ResponseEntity<Product> replace(@PathVariable long id, @RequestBody UpdateProductRequest request) {        return ResponseEntity.of(productService.replace(id, request));    }
    @PatchMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)    public ResponseEntity<Product> patch(@PathVariable long id, @RequestBody PatchProductRequest request) {        return ResponseEntity.of(productService.patch(id, request));    }
    @DeleteMapping("/{id}")    public ResponseEntity<Void> delete(@PathVariable long id) {        if (productService.delete(id)) {            return ResponseEntity.noContent().build();        }        return ResponseEntity.notFound().build();    }}
Output
(no output: Examples 3 and 4 call the list with different parameters)

What this code does

  • categoryId uses required = false (so it is a Long, null when missing); minPrice and maxPrice use Optional; includeInactive, page and size use defaultValue. All three styles make a parameter optional.
  • The controller passes the values to ProductService.search, which skips each filter that is null, then PageResponse.of cuts out one page. The service now also holds product 15, the inactive USB-C cable from the seed data.
  • PageResponse is generic (<T>), so customers and orders reuse it later. (long) page * size avoids an int overflow for a huge page number.

Example 3 · Defaults, includeInactive and the second page

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
curl http://localhost:8080/api/v1/productscurl "http://localhost:8080/api/v1/products?includeInactive=true&size=3"curl "http://localhost:8080/api/v1/products?includeInactive=true&size=3&page=1"
Output
$ curl http://localhost:8080/api/v1/products
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true},{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true},{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1299.00,"stock":120,"isActive":true},{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":30,"isActive":true}],"page":0,"size":20,"totalElements":5,"totalPages":1}
$ curl "http://localhost:8080/api/v1/products?includeInactive=true&size=3"
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true},{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true}],"page":0,"size":3,"totalElements":6,"totalPages":2}
$ curl "http://localhost:8080/api/v1/products?includeInactive=true&size=3&page=1"
{"content":[{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1299.00,"stock":120,"isActive":true},{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":30,"isActive":true},{"id":15,"sku":"ACC-USBC1","name":"USB-C Cable 1m","categoryId":4,"categoryName":"Accessories","price":199.00,"stock":0,"isActive":false}],"page":1,"size":3,"totalElements":6,"totalPages":2}

What this code does

  • With no parameters the defaults apply: page 0, size 20, only active products. That is 5 products on 1 page.
  • includeInactive=true adds product 15, so there are 6 products; size=3 splits them into 2 pages.
  • Pages start at 0, so page=1 is the second page, ending with the inactive cable ("isActive":false).

Three ways make it optional. defaultValue = "20" uses that value when the parameter is missing or empty. required = false gives null, so the type must be a wrapper such as Long, never long. An Optional<BigDecimal> parameter gives Optional.empty().

The ShopLite contract fixes the defaults: page 0, size 20, and filters off unless sent. The list now returns the contract's page envelope, a small PageResponse record with content, page, size, totalElements and totalPages. The Request and response DTOs lesson explains why a page object beats a bare array.

Several query parameters together

A page envelope is the response object that wraps one page of items with content, page, size, totalElements and totalPages, so a client can page through a long list.

Query parameters combine with & in any order. ?categoryId=2&minPrice=18000&page=0 means "Mobiles from Rs 18,000, first page"; each one maps to its own @RequestParam, and the filters apply together (AND).

Example 4 · Filters together, an empty result and ignored parameters

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
curl "http://localhost:8080/api/v1/products?categoryId=2&minPrice=18000&page=0&size=20"curl "http://localhost:8080/api/v1/products?maxPrice=1000"curl "http://localhost:8080/api/v1/products?categoryId=99"curl "http://localhost:8080/api/v1/products?colour=red&size=2"curl "http://localhost:8080/api/v1/products?categoryid=2&size=2"
Output
$ curl "http://localhost:8080/api/v1/products?categoryId=2&minPrice=18000&page=0&size=20"
{"content":[{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true},{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true}],"page":0,"size":20,"totalElements":2,"totalPages":1}
$ curl "http://localhost:8080/api/v1/products?maxPrice=1000"
{"content":[{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":30,"isActive":true}],"page":0,"size":20,"totalElements":1,"totalPages":1}
$ curl "http://localhost:8080/api/v1/products?categoryId=99"
{"content":[],"page":0,"size":20,"totalElements":0,"totalPages":0}
$ curl "http://localhost:8080/api/v1/products?colour=red&size=2"
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":0,"size":2,"totalElements":5,"totalPages":3}
$ curl "http://localhost:8080/api/v1/products?categoryid=2&size=2"
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":0,"size":2,"totalElements":5,"totalPages":3}

What this code does

  • Mobiles from Rs 18,000 leaves the Galaxy M35 and the iPhone: the Redmi at 17,999 is just below the limit. minPrice and maxPrice include the limit itself.
  • Category 99 has no products, so the answer is 200 with an empty content and totalPages 0. Quote the URL in the shell: an unquoted & would end the command in bash and break it in PowerShell.
  • colour is unknown and ignored. categoryid (small i) is also unknown, so the "filter" does nothing: totalElements is 5, every active product.

Two rules from the contract shape the results. A filter that matches nothing returns 200 with an empty page, not 404: the list exists, it is just empty. A parameter the server does not know, such as colour=red, is ignored.

An ignored parameter hides typos. Parameter names are case-sensitive, so categoryid=2 is an unknown parameter and the client silently gets every product. When a filter "does not work", compare the spelling with the method's parameter first.

Type conversion and the 400 for /api/v1/products/abc

Type conversion turns the text in a URL into the Java type of the parameter: "3" into long, "18000" into BigDecimal, "true" into boolean. Text that cannot be converted gets 400 Bad Request.

A client types abc where a number belongs, and Spring must refuse it before your code runs. The examples send values that cannot be converted, and values that convert but are wrong.

Example 5 · Values that cannot be converted: 400

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
curl -i http://localhost:8080/api/v1/products/abccurl -i "http://localhost:8080/api/v1/products?size=ten"curl -i "http://localhost:8080/api/v1/products?minPrice=abc"
Sample output
$ curl -i http://localhost:8080/api/v1/products/abc
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:58:22 GMT
Connection: close

{"timestamp":"2026-10-16T04:58:22.226Z","status":400,"error":"Bad Request","path":"/api/v1/products/abc"}
$ curl -i "http://localhost:8080/api/v1/products?size=ten"
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:58:22 GMT
Connection: close

{"timestamp":"2026-10-16T04:58:22.753Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
$ curl -i "http://localhost:8080/api/v1/products?minPrice=abc"
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:58:22 GMT
Connection: close

{"timestamp":"2026-10-16T04:58:22.954Z","status":400,"error":"Bad Request","path":"/api/v1/products"}

Server log:
WARN ... Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Method parameter 'id': Failed to convert value of type 'java.lang.String' to required type 'long'; For input string: "abc"]
WARN ... Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Method parameter 'size': Failed to convert value of type 'java.lang.String' to required type 'int'; For input string: "ten"]
WARN ... Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Method parameter 'minPrice': Failed to convert value of type 'java.lang.String' to required type 'java.util.Optional'; ...]

What this code does

  • Each bad value stops the request before the controller method runs: the client gets 400 and the method never sees "abc".
  • The response body only says "Bad Request". The log names the parameter (id, size, minPrice), the target type and the input, so read the log first.
  • For Optional<BigDecimal> the log names the type as java.util.Optional; the conversion of the inner BigDecimal is what failed.

Example 6 · Converted but wrong: size=0 and includeInactive=yes

Runs in: the rest-lab practice project (Spring Boot 4.1)

Terminal
curl -i "http://localhost:8080/api/v1/products?size=0"curl "http://localhost:8080/api/v1/products?includeInactive=yes&size=1"
Sample output
$ curl -i "http://localhost:8080/api/v1/products?size=0"
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:58:23 GMT
Connection: close

{"timestamp":"2026-10-16T04:58:23.342Z","status":500,"error":"Internal Server Error","path":"/api/v1/products"}
$ curl "http://localhost:8080/api/v1/products?includeInactive=yes&size=1"
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}],"page":0,"size":1,"totalElements":6,"totalPages":6}

Server log:
ERROR ... Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.ArithmeticException: / by zero] with root cause

What this code does

  • 0 is a valid int, so conversion passes and PageResponse.of divides by zero: the client gets 500 for its own mistake. The contract says size must be 1 to 100 and anything else is 400; the Validation module adds that check.
  • yes converts to true (Spring also accepts on and 1), so totalElements is 6: the inactive cable is counted.
  • Lesson: conversion only proves the type. Every limit needs a real check.

Conversion only checks the type, not whether the value makes sense. size=0 is a valid int, so it reaches the code and divides by zero: a 500. boolean also accepts yes, on and 1 as true. Ranges such as "size between 1 and 100" are rules, and the Validation module checks them and answers 400.

The default 400 body says only "Bad Request". The log line has the details, and the Exception handling module puts them into the response.

Fix the error

Fix the parameter

Each call fails with the error shown. Pick the line that fixes the parameter.

Round 1 of 2

GET /api/v1/products without ?size must use 20.

@GetMapping
public PageResponse<Product> list(
@RequestParam(required = false) int size) {
return service.list(size);
}

Error

Optional int parameter 'size' is present but cannot be translated into a null value
due to being declared as a primitive type.

Path variable or query parameter: how to choose

A path variable names a resource; a query parameter changes how a resource is shown. Ask: "Without this value, is it a different thing?" If yes, it belongs in the path. If it only filters, sorts or pages the same list, it belongs in the query.

  • Identity: /products/3, /customers/1/addresses/2, /orders/14/items
  • Filters and search: ?categoryId=2, ?q=redmi, ?status=PLACED
  • Paging and sorting: ?page=1&size=20&sort=price,desc
  • Optional input is always a query parameter; a path part cannot be "left out"

The contract shows both for products: GET /products/{id} reads one, GET /products?categoryId=2 filters the list. Writing /products/category/2 would invent a second, competing URL for the same list.

Next step

Check your understanding

12 quick questions