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 create a REST API using Java Spring Boot

Creating a RESTful API with Spring Boot is quite straightforward due to the framework's extensive support for building web applications. Here's a step-by-step guide to building a basic REST API using Spring Boot:

1. Setup New Spring Boot Project:

You can bootstrap a new Spring Boot project using Spring Initializr. Select the necessary dependencies, especially "Spring Web" to enable web support.

2. Project Structure:

After creating the project, you will have the following structure:

  • src/main/java: Java source files.
  • src/main/resources: Configuration and static files.
  • src/test/java: Test source files.

3. Create an Entity:

This represents a data object you want to manage with your REST API. For instance, let's manage a simple Book entity.

public class Book {
    private Long id;
    private String title;
    private String author;

    // Constructors, getters, setters, etc.
}

4. Create a Controller:

Controllers manage incoming HTTP requests and send responses. Here's a basic BookController:

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

    // For the sake of simplicity, let's use an in-memory list
    private List<Book> books = new ArrayList<>();

    @GetMapping
    public List<Book> getAllBooks() {
        return books;
    }

    @GetMapping("/{id}")
    public Book getBook(@PathVariable Long id) {
        return books.stream()
                    .filter(b -> b.getId().equals(id))
                    .findFirst()
                    .orElse(null); // Add proper error handling here
    }

    @PostMapping
    public Book createBook(@RequestBody Book book) {
        books.add(book);
        return book;
    }

    // You can also add PUT and DELETE endpoints as needed
}

5. Configure Spring Boot:

Most of Spring Boot's configuration is convention-over-configuration, so it works out of the box. However, you can specify properties in application.properties or application.yml in src/main/resources.

For instance, to change the port:

server.port=8085

6. Run the Application:

Run the main class generated by Spring Initializr (it should have @SpringBootApplication annotation) either from your IDE or by using Maven/Gradle.

For Maven:

mvn spring-boot:run

For Gradle:

./gradlew bootRun

7. Testing:

With your application running, you can test the API using tools like Postman, Insomnia, or just using curl from the command line.

For example:

curl -X GET http://localhost:8085/api/books

8. Enhancements:

  • Error Handling: Add proper error handling for invalid input, missing resources, etc.
  • Data Persistence: Integrate with databases using Spring Data JPA or another appropriate Spring Data project.
  • Validation: Use Bean Validation to validate incoming data.
  • Security: Secure your API using Spring Security if needed.
  • Documentation: Use tools like Swagger (with Springfox) or Springdoc OpenAPI to document your REST API.

This is a simple and straightforward way to create a RESTful API using Spring Boot. As you develop more complex applications, you may need to add more configurations, services, repositories, and other components.

  1. Building a Hello World RESTful API with Spring Boot:

    • Description: Create a simple RESTful API with a "Hello, World!" endpoint.
    • Code:
      @RestController
      public class HelloWorldController {
      
          @GetMapping("/hello")
          public String sayHello() {
              return "Hello, World!";
          }
      }
      
  2. Creating RESTful endpoints in Java with Spring Boot:

    • Description: Define additional RESTful endpoints for various HTTP methods.
    • Code:
      @RestController
      public class ApiController {
      
          @GetMapping("/api/greet")
          public String greet() {
              return "Greetings!";
          }
      
          // Add more endpoints for POST, PUT, DELETE, etc.
      }
      
  3. Basic controller and request mapping in Spring Boot for REST:

    • Description: Set up a basic controller with request mappings to handle RESTful requests.
    • Code:
      @RestController
      @RequestMapping("/api")
      public class ApiController {
      
          @GetMapping("/resource")
          public String getResource() {
              return "This is a REST resource!";
          }
      }
      
  4. Using annotations for RESTful services in Spring Boot:

    • Description: Leverage annotations such as @RestController and @RequestMapping to simplify the creation of RESTful services.
    • Code:
      @RestController
      @RequestMapping("/api")
      public class ApiController {
      
          @GetMapping("/data")
          public String getData() {
              return "Data from RESTful service";
          }
      }
      
  5. Handling request parameters and path variables in Spring Boot:

    • Description: Extract data from request parameters and path variables in Spring Boot REST controllers.
    • Code:
      @GetMapping("/user")
      public String getUser(@RequestParam String username) {
          return "Hello, " + username + "!";
      }
      
      @GetMapping("/user/{id}")
      public String getUserById(@PathVariable Long id) {
          return "User ID: " + id;
      }
      
  6. Returning JSON responses from a Spring Boot REST API:

    • Description: Configure Spring Boot to automatically serialize Java objects to JSON for API responses.
    • Code:
      @RestController
      public class UserController {
      
          @GetMapping("/user")
          public User getUser() {
              User user = new User("John", "Doe");
              return user;
          }
      }
      
      // User class with getters and setters