Introduction

Spring Boot makes it easy to build RESTful APIs quickly. In this tutorial, we'll guide you through creating a simple REST API using Spring Boot. We'll cover the basic steps and provide you with sample code.


Prerequisites

Before you begin, make sure you have the following prerequisites:


Create a New Spring Boot Project

Start by creating a new Spring Boot project. Here's how:

  1. Open your IDE and select "File" > "New" > "Project..."
  2. Choose "Spring Initializr" or "Spring Boot" as the project type.
  3. Configure your project settings, such as the project name, package, and dependencies. For a REST API, you'll need to include "Spring Web."
  4. Click "Finish" to create the project.

Write a Simple REST Controller

Now, let's create a REST controller to handle HTTP requests. Here's a basic example:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiController { @GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}

This code defines a simple REST controller with an endpoint /api/hello that returns the string "Hello, World!" when accessed.


Run Your REST API

To run your Spring Boot application and test the REST API, follow these steps:

  1. Right-click your main class and select "Run" or "Debug."
  2. Once the application is running, open a web browser or use a tool like Postman to send a GET request to http://localhost:8080/api/hello.
  3. You should receive the "Hello, World!" response.

Conclusion

Congratulations! You've created a simple REST API with Spring Boot. This is just the beginning; you can expand and enhance your API to handle more complex operations and data.