Handling Parameters in REST Controllers

Spring Boot offers several ways to handle parameters in REST controllers. We’ll cover the three main types: query parameters, path variables, and request bodies.

Query Parameters with @RequestParam

Query parameters are key-value pairs in the URL after the ‘?’ character.

@GetMapping("/users")
public List<User> getUsers(@RequestParam(required = false) String name) {
    // If name is provided, filter users by name
    // Otherwise, return all users
}

In this example, a request to /users?name=John would filter users named John.

Path Variables with @PathVariable

Path variables are parts of the URL path that are extracted as parameters.

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
    // Retrieve user with the given id
}

Here, a request to /users/123 would retrieve the user with id 123.

Request Bodies with @RequestBody

Request bodies are used to send complex data, typically with POST or PUT requests.

@PostMapping("/users")
public User createUser(@RequestBody User user) {
    // Create a new user with the provided data
}

This method expects a JSON representation of a User object in the request body.

Combining Different Parameter Types

You can combine these different types of parameters in a single method:

@PutMapping("/users/{id}")
public User updateUser(
    @PathVariable Long id,
    @RequestBody User user,
    @RequestParam(required = false) Boolean sendEmail
) {
    // Update user with id, using data from user object
    // If sendEmail is true, send a notification email
}

This method uses a path variable for the user ID, a request body for the updated user data, and a query parameter to determine if an email should be sent.

Best Practices

Best Practices

  1. Use @PathVariable for identifying resources in the URL.

  2. Use @RequestParam for query parameters. Remember, they’re optional by default.

  3. Only use @RequestParam(required = true) when the parameter is absolutely necessary.

  4. Provide default values for optional parameters when it makes sense, using @RequestParam(defaultValue = "someValue").

  5. Use @RequestBody for sending complex data in POST and PUT requests.

  6. Keep GET requests idempotent and safe - use query parameters, not request bodies.

  7. For PUT and POST, send data in the request body, not as query parameters.

  8. Validate input data to ensure data integrity and security.

  9. Be aware of default HTTP status codes: - Spring Boot returns 200 OK for successful requests by default. - 404 Not Found is returned if the requested resource doesn’t exist. - 400 Bad Request is returned for client-side errors (e.g., invalid parameters). - 500 Internal Server Error is returned for unhandled exceptions.

  10. Use DTOs (Data Transfer Objects) to control what data is sent and received.

By effectively using these parameter handling techniques, you can create flexible and powerful REST APIs in Spring Boot.