Creating Rest Controllers

Spring Boot offers several ways to handle parameters in REST controllers. We’ll cover the three main types: path variables, query parameters, and request bodies, focusing on their typical use cases and best practices.

Path Variables with @PathVariable

Path variables are parts of the URL path that are extracted as parameters. They’re commonly used to identify specific resources.

@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.

Query Parameters with @RequestParam

Query parameters are key-value pairs in the URL after the ‘?’ character. They’re often used for filtering, sorting, or pagination.

@GetMapping("/users")
public List<User> getUsers(
    @RequestParam String name,
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "10") int size
) {
    // Filter users by name
    // Use page and size for pagination
}

In this example, a request to /users?name=John&page=1&size=20 would filter users named John, returning the second page with 20 users per page.

Note: @RequestParam is optional by default. Use required = true if the parameter must be present.

Request Bodies with @RequestBody

Request bodies are used to send complex data, typically with POST or PUT requests. This is the most common way to send data for creation or update operations.

@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.

For PUT requests:

@PutMapping("/users/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
    // Update user with id, using data from user object
}

Handling Different HTTP Methods

Different HTTP methods typically handle parameters differently:

  • GET: Uses @RequestParam for filtering/pagination and @PathVariable for resource identification.

  • POST: Primarily uses @RequestBody for sending data to be created.

  • PUT: Uses @PathVariable to identify the resource and @RequestBody for the updated data.

  • DELETE: Typically only uses @PathVariable to identify the resource to be deleted.

Example:

@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Long id) {
    // Delete user with the given id
}

Best Practices

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

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

  3. If a query parameter is required, use @RequestParam(required = true).

  4. Provide default values for optional parameters when it makes sense.

  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. Use appropriate HTTP status codes in your responses.

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

By following these practices and understanding the appropriate use of different parameter types, you can create RESTful APIs that are robust, easy to use, and conform to standard conventions.