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:
- Java Development Kit (JDK) installed
- An Integrated Development Environment (IDE) like Spring Tool Suite or IntelliJ IDEA
Create a New Spring Boot Project
Start by creating a new Spring Boot project. Here's how:
- Open your IDE and select `File` > `New` > `Project...`
- Choose `Spring Initializr` or `Spring Boot` as the project type.
- Configure your project settings, such as the project name, package, and dependencies. For a REST API, you'll need to include `Spring Web.`
- 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:
- Right-click your main class and select `Run` or `Debug.`
- 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. - 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.
