Building a RESTful API with Spring Boot: A Comprehensive Guide with annotations

    Spring Boot: End to end example with annotations

    Note: You can create and download the sample maven Spring Boot application by using Spring Starter website - https://start.spring.io/

    1. Create a Spring Boot Application Class: 
    • @SpringBootApplication: This annotation is the heart of a Spring Boot application. It is a combination of three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan
    • This single annotation initializes the Spring context, enables auto-configuration, and scans for Spring components within the package and its sub-packages.
      • Use Case: Place this annotation on the main class of your Spring Boot application to bootstrap the application.
                BookApplication.java

                import org.springframework.boot.SpringApplication;
                import org.springframework.boot.autoconfigure.SpringBootApplication;

                @SpringBootApplication
                public class BookApplication {
                    public static void main(String[] args) {
                        SpringApplication.run(BookApplication.class, args);
                    }
                }


        2. Create a Book Entity:

    • @Entity: Marks the Book class as an entity, allowing it to be persisted in the database.

                Book.java

                import javax.persistence.Entity;
                import javax.persistence.GeneratedValue;
                import javax.persistence.GenerationType;
                import javax.persistence.Id;

                @Entity
                public class Book {
                    @Id
                    @GeneratedValue(strategy = GenerationType.IDENTITY)
                    private Long id;
                    private String title;
                    private String author;

                    // Constructors, getters, and setters (or) use Lombok @Data annotation
                }

        3. Create a Book Repository:

    • @Repository: Not shown explicitly, but Spring Data JPA automatically detects the BookRepository interface as a repository and provides implementation for CRUD operations.

                BookRepository.java

                import org.springframework.data.jpa.repository.JpaRepository;
                
                @Repository
                public interface BookRepository extends JpaRepository<Book, Long> {
                    // Custom queries if needed - @Query("your custom query here")
                }


        4. Create a REST Controller:

    • @RestController: Marks the BookController class as a REST controller, allowing it to handle HTTP requests.
    • @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: Define the endpoints for the REST API and map them to specific controller methods.
    • @Autowired: Injects the BookRepository bean into the BookController constructor.

                BookController.java

                import org.springframework.beans.factory.annotation.Autowired;
                import org.springframework.web.bind.annotation.*;

                import java.util.List;

                @RestController
                @RequestMapping("/api/books")
                public class BookController {
                    private final BookRepository bookRepository;

                    @Autowired
                    public BookController(BookRepository bookRepository) {
                        this.bookRepository = bookRepository;
                    }

                    @GetMapping
                    public List<Book> getAllBooks() {
                        return bookRepository.findAll();
                    }

                    @GetMapping("/{id}")
                    public Book getBookById(@PathVariable Long id) {
                        return bookRepository.findById(id)
                                .orElseThrow(() -> new ResourceNotFoundException("Book not found with id: " + id));
                    }

                    @PostMapping
                    public Book createBook(@RequestBody Book book) {
                        return bookRepository.save(book);
                    }

                    @PutMapping("/{id}")
                    public Book updateBook(@PathVariable Long id, @RequestBody Book book) {
                        Book existingBook = bookRepository.findById(id)
                                .orElseThrow(() -> new ResourceNotFoundException("Book not found with id: " + id));
                        existingBook.setTitle(book.getTitle());
                        existingBook.setAuthor(book.getAuthor());
                        return bookRepository.save(existingBook);
                    }

                    @DeleteMapping("/{id}")
                    public void deleteBook(@PathVariable Long id) {
                        bookRepository.deleteById(id);
                    }
                }


        5. Create a Custom Exception Handler: Resulting HTTP Response (optional) :
    • If the book with the given id is not found, Spring will catch the ResourceNotFoundException, and as a result of the @ResponseStatus(HttpStatus.NOT_FOUND) annotation, the HTTP response will have a status code of 404 (Not Found). The response will look like this:

            HTTP/1.1 404 Not Found
    Content-Type: application/json
    Date: [Current Date]

    {
       "message": "Book not found with id: [id]"
    }
    • By using the @ResponseStatus annotation, we can easily control the HTTP status codes returned to the client in specific scenarios, making it easier to communicate the status of the request and handle errors gracefully.


                ResourceNotFoundException.java

                import org.springframework.http.HttpStatus;
                import org.springframework.web.bind.annotation.ResponseStatus;

                @ResponseStatus(HttpStatus.NOT_FOUND)
                public class ResourceNotFoundException extends RuntimeException {
                    public ResourceNotFoundException(String message) {
                        super(message);
                    }
                }

        
        6. Enable Caching (optional) :

    • @EnableCaching: Enables Spring's caching support in the application (not shown with actual caching logic).

                CachingConfig.java

                import org.springframework.cache.annotation.EnableCaching;
                import org.springframework.context.annotation.Configuration;

                @Configuration
                @EnableCaching
                public class CachingConfig {
                    // Caching configuration (if needed)
                }


        Remember that this is just a basic example to illustrate the usage of the annotations. In a real-world scenario, you might want to add more features, validation, error handling, security configurations, etc., based on your application requirements.




    Tags: , , , , , , , , , , ,

    0 Responses to “Building a RESTful API with Spring Boot: A Comprehensive Guide with annotations”

    Post a Comment

    Thanks for your comments

    Subscribe

    © 2014 Java Frameworks. All rights reserved.
    Designed by Blogger