Complete Guide to Passing Multiple Parameters in Spring REST APIs

Nov 20, 2025 · Programming · 11 views · 7.8

Keywords: Spring Framework | REST API | Parameter Passing | Query Parameters | Path Parameters | JSON Processing

Abstract: This comprehensive guide explores various methods for passing parameters to REST APIs in the Spring framework, including query parameters, path parameters, and request body parameters. Through detailed code examples and best practice analysis, it helps developers understand how to properly handle simple parameters and complex JSON objects while avoiding common 415 and 404 errors. The article also discusses parameter type selection strategies and RESTful API design principles, providing complete guidance for building robust web services.

Fundamentals of REST API Parameter Passing

In modern web development, parameter passing in REST APIs is a core technology for building flexible service interfaces. The Spring framework provides multiple mechanisms to handle different types of parameters, each with specific application scenarios and advantages.

Usage and Parsing of Query Parameters

Query parameters are the most common method for parameter passing, suitable for optional or non-critical filtering conditions. In Spring, the @RequestParam annotation can be used to directly map query parameters from the URL.

Here is a complete example for handling multiple query parameters:

@RestController
@RequestMapping("/api/v1")
public class BookController {
    
    @GetMapping("/mno/objectKey")
    public ResponseEntity<Book> getBookByParams(
            @RequestParam Long id,
            @RequestParam String name) {
        
        Book book = bookService.findBookByIdAndName(id, name);
        if (book != null) {
            return ResponseEntity.ok(book);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

The corresponding URL invocation format is: http://localhost:8080/api/v1/mno/objectKey?id=1&name=saif. The advantage of this approach is that parameter order doesn't matter, and optional parameters can be flexibly added or omitted.

Configuration and Application of Path Parameters

Path parameters are suitable for identifying resource uniqueness and are typically part of the URL path. Spring captures these parameters through the @PathVariable annotation.

Consider the following implementation for handling path parameters:

@GetMapping("/mno/objectKey/{id}/{name}")
public ResponseEntity<Book> getBookByPath(
        @PathVariable("id") Long bookId,
        @PathVariable("name") String bookName) {
    
    Book book = bookService.findBookByIdAndName(bookId, bookName);
    return book != null ? ResponseEntity.ok(book) : ResponseEntity.notFound().build();
}

The corresponding URL format is: http://localhost:8080/api/v1/mno/objectKey/1/saif. Path parameters make URLs more semantic but require all parameters to be provided in a fixed order.

Handling Complex Parameter Structures

When needing to pass complex nested data structures, placing JSON objects directly in URL paths or query parameters is inappropriate. The fundamental issue with this approach lies in URL limitations regarding special characters and encoding complexity.

Analysis of incorrect examples: Attempting to use JSON objects as path parameters like http://localhost:8080/api/v1/mno/objectKey/{"id":1,"name":"Saif"} will cause URL parsing failures because characters like braces and quotes require complex URL encoding, and Spring cannot directly map them to objects.

The correct approach is to use POST requests with request bodies for transmitting complex data:

@PostMapping(value = "/mno/objectKey", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Book> createOrUpdateBook(@RequestBody BookRequest request) {
    
    Book book = bookService.processComplexBookData(request);
    return ResponseEntity.status(HttpStatus.CREATED).body(book);
}

// Corresponding request body data structure
class BookRequest {
    private Long id;
    private String name;
    private List<Category> categories;
    
    // Standard getter and setter methods
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public List<Category> getCategories() { return categories; }
    public void setCategories(List<Category> categories) { this.categories = categories; }
}

class Category {
    private Long categoryId;
    private Long timestamp;
    
    public Long getCategoryId() { return categoryId; }
    public void setCategoryId(Long categoryId) { this.categoryId = categoryId; }
    public Long getTimestamp() { return timestamp; }
    public void setTimestamp(Long timestamp) { this.timestamp = timestamp; }
}

Advanced Parameter Mapping Techniques

For dynamic or unknown numbers of parameters, Spring provides more flexible handling methods. Using Map<String, String> can capture all query parameters:

@GetMapping("/custom")
public ResponseEntity<Map<String, Object>> handleCustomQuery(
        @RequestParam Map<String, String> queryParams) {
    
    Map<String, Object> response = new HashMap<>();
    queryParams.forEach((key, value) -> {
        response.put("received_" + key, value);
    });
    
    return ResponseEntity.ok(response);
}

This approach is particularly suitable for scenarios like search filtering and sorting, where the number and names of parameters may change dynamically.

Common Errors and Solutions

During parameter processing, developers often encounter typical errors. 415 errors usually stem from Content-Type mismatches, while 404 errors are often due to incorrect URL path mapping.

Solving 415 errors: Ensure proper setting of the consumes attribute when consuming JSON data and specify Content-Type: application/json in request headers.

Preventing 404 errors: Carefully check if URL path patterns completely match those defined in controller methods' @RequestMapping, including the position and names of path parameters.

Best Practices for Parameter Type Selection

According to RESTful API design principles, parameter type selection should be based on semantic meaning: use path parameters to identify specific resources, query parameters for filtering and sorting, and request bodies for creation or update operations.

Considering performance aspects, query parameters are suitable for caching, while path parameters are better for CDN optimization. For sensitive data, avoid passing it in URLs and instead use request headers or encrypted request bodies.

Testing and Validation Strategies

Comprehensive testing is crucial for ensuring correct parameter processing. It is recommended to use the Spring Boot Test framework to write integration tests that verify processing results for various parameter combinations.

@SpringBootTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class BookControllerTest {
    
    @Autowired
    private TestRestTemplate restTemplate;
    
    @Test
    void testQueryParameters() {
        String url = "http://localhost:8080/api/v1/mno/objectKey?id=1&name=test";
        ResponseEntity<Book> response = restTemplate.getForEntity(url, Book.class);
        
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).isNotNull();
        assertThat(response.getBody().getId()).isEqualTo(1L);
    }
    
    @Test
    void testPathParameters() {
        String url = "http://localhost:8080/api/v1/mno/objectKey/1/test";
        ResponseEntity<Book> response = restTemplate.getForEntity(url, Book.class);
        
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    }
}

Through comprehensive test coverage, you can ensure API stability and correctness across various parameter scenarios.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.