Creating Your First REST API with Spring Boot
Spring Boot makes it incredibly easy to create RESTful web services with minimal setup. As a Java developer, building your first REST API using Spring Boot can be a great way to understand the power and simplicity of the framework. In this blog, we’ll walk through the steps to build a basic REST API that performs simple operations like retrieving and adding data.
What is a REST API?
REST (Representational State Transfer) is an architectural style used for designing web services that communicate over HTTP. A REST API allows clients to interact with the server using standard HTTP methods like GET, POST, PUT, and DELETE.
Step 1: Set Up the Project
Use Spring Initializr to generate a new Spring Boot project:
Project Type: Maven
Language: Java
Dependencies: Spring Web
Download and unzip the project, then open it in your IDE (e.g., IntelliJ IDEA or Eclipse).
Step 2: Create a Model Class
Create a simple User class to represent data.
public class User {
private Long id;
private String name;
// Constructors, getters, and setters
}
Step 3: Create a REST Controller
Create a controller class to handle API requests.
@RestController
@RequestMapping("/api/users")
public class UserController {
private List<User> users = new ArrayList<>();
@GetMapping
public List<User> getAllUsers() {
return users;
}
@PostMapping
public User addUser(@RequestBody User user) {
users.add(user);
return user;
}
}
@RestController makes the class a REST controller.
@RequestMapping defines the base URL.
@GetMapping and @PostMapping handle HTTP GET and POST requests respectively.
@RequestBody maps incoming JSON to a Java object.
Step 4: Run the Application
Run the application using:
./mvnw spring-boot:run
Or simply run the main method in the Application class. Once the server starts, you can access your API:
GET http://localhost:8080/api/users – Retrieves all users
POST http://localhost:8080/api/users – Adds a new user (with JSON body)
Step 5: Test Your API
Use tools like Postman or cURL to test your endpoints. Send a JSON body like:
{
"id": 1,
"name": "Alice"
}
Conclusion
Spring Boot simplifies REST API development by handling configuration and boilerplate code for you. With just a few lines of code, you can build and run a working API. As you grow more comfortable, you can add features like validation, database integration, and exception handling to make your APIs production-ready.
Learn Full Stack Java Training
Working with Dates and Time in Java
Java 8 to Java 17: Key Features
Java Best Practices for Beginners
Introduction to Spring Boot for Java Developers
Visit Our Quality Thought Training Institute
Comments
Post a Comment