Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

How to Make Put Request in Spring Boot?

To make a PUT request in Spring Boot, you can use the @PutMapping annotation in a RestController. Let's walk through the process with an example:

1. Create a Spring Boot Project:

If you haven't already, initialize a new Spring Boot project using Spring Initializr with the "Web" dependency.

2. Create a Model:

Let's assume you have a simple Book model:

public class Book {

    private Long id;
    private String title;
    private String author;

    // Constructors, getters, setters, etc.
}

3. Create the RestController:

Now, create a RestController that provides a PUT endpoint to update a book:

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {

    // This is a simple in-memory list for demonstration purposes.
    private List<Book> books = new ArrayList<>();

    @GetMapping("/{id}")
    public Book getBookById(@PathVariable Long id) {
        return books.stream()
            .filter(book -> book.getId().equals(id))
            .findFirst()
            .orElse(null); // Or throw an exception
    }

    @PutMapping("/{id}")
    public Book updateBook(@PathVariable Long id, @RequestBody Book updatedBook) {
        Book existingBook = getBookById(id);
        if (existingBook != null) {
            existingBook.setTitle(updatedBook.getTitle());
            existingBook.setAuthor(updatedBook.getAuthor());
        }
        return existingBook; // Or throw an exception if not found
    }
}

In the code above, the updateBook method listens to PUT requests on the /api/books/{id} path. The @RequestBody annotation tells Spring to deserialize the JSON request body into a Book object, and the @PathVariable annotation captures the {id} from the path.

4. Test the PUT Endpoint:

With the application running, you can use tools like Postman to test the PUT endpoint:

  • Get a book by ID: GET http://localhost:8080/api/books/{id}

  • Update a book: PUT http://localhost:8080/api/books/{id} with a JSON body like:

    {
      "title": "Updated Title",
      "author": "Updated Author"
    }
    

Remember, this example uses an in-memory list for simplicity. In real-world scenarios, you would typically interact with a service layer and a database, handle exceptions, add validation, and possibly handle other aspects like security and transaction management.

  1. Configuring a Spring Boot RestController for PUT operations:

    @RestController
    @RequestMapping("/api/resource")
    public class ResourceController {
    
        @PutMapping("/{id}")
        public ResponseEntity<String> updateResource(@PathVariable Long id, @RequestBody Resource resource) {
            // Logic to update resource
            return ResponseEntity.ok("Resource updated successfully");
        }
    }
    
  2. Mapping and processing PUT requests in Spring Boot application:

    @PutMapping("/update")
    public ResponseEntity<String> updateResource(@RequestBody Resource resource) {
        // Logic to update resource
        return ResponseEntity.ok("Resource updated successfully");
    }
    
  3. Using @PutMapping annotation for PUT requests in Spring Boot:

    @PutMapping("/update/{id}")
    public ResponseEntity<String> updateResource(@PathVariable Long id, @RequestBody Resource resource) {
        // Logic to update resource
        return ResponseEntity.ok("Resource updated successfully");
    }
    
  4. Handling request parameters and request body in Spring Boot PUT:

    @PutMapping("/update")
    public ResponseEntity<String> updateResource(@RequestParam Long id, @RequestBody Resource resource) {
        // Logic to update resource
        return ResponseEntity.ok("Resource updated successfully");
    }
    
  5. Updating resources with PUT requests in a Spring Boot API:

    @PutMapping("/update/{id}")
    public ResponseEntity<String> updateResource(@PathVariable Long id, @RequestBody Resource resource) {
        // Logic to update resource based on id
        return ResponseEntity.ok("Resource updated successfully");
    }
    
  6. Validating and processing data in PUT requests in Spring Boot:

    @PutMapping("/update/{id}")
    public ResponseEntity<String> updateResource(@PathVariable Long id, @Valid @RequestBody Resource resource) {
        // Logic to update resource
        return ResponseEntity.ok("Resource updated successfully");
    }
    
  7. Securing PUT endpoints in Spring Boot RestController:

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PutMapping("/update/{id}")
    public ResponseEntity<String> updateResource(@PathVariable Long id, @RequestBody Resource resource) {
        // Logic to update resource
        return ResponseEntity.ok("Resource updated successfully");
    }
    
  8. Handling custom headers and content types in Spring Boot PUT:

    @PutMapping(value = "/update/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> updateResource(@PathVariable Long id, @RequestBody Resource resource) {
        // Logic to update resource
        return ResponseEntity.ok("Resource updated successfully");
    }
    
  9. Configuring cross-origin resource sharing (CORS) for PUT requests:

    @CrossOrigin(origins = "http://allowed-origin.com")
    @PutMapping("/update/{id}")
    public ResponseEntity<String> updateResource(@PathVariable Long id, @RequestBody Resource resource) {
        // Logic to update resource
        return ResponseEntity.ok("Resource updated successfully");
    }
    
  10. Using ResponseEntity for customized responses in Spring Boot PUT:

    @PutMapping("/update/{id}")
    public ResponseEntity<MyResponse> updateResource(@PathVariable Long id, @RequestBody Resource resource) {
        // Logic to update resource
        MyResponse response = new MyResponse("Resource updated successfully");
        return new ResponseEntity<>(response, HttpStatus.OK);
    }