Building Your First REST API with Spring Boot 2
Spring Boot has become one of the most popular frameworks for building robust and scalable Java applications. One of its most common uses is to create RESTful APIs, which are a cornerstone of modern web applications. In this article, we’ll walk you through the steps of building your first REST API with Spring Boot.
What is Spring Boot?
Spring Boot is an extension of the Spring framework that simplifies the setup, configuration, and deployment of Spring applications. It allows developers to get started quickly without having to deal with the boilerplate setup required in traditional Spring applications. Spring Boot achieves this through:
Convention over configuration: Sensible defaults for most project settings.
Embedded servers: Tomcat, Jetty, or Undertow are embedded, so no need to deploy WAR files.
Production-ready features: Health checks, metrics, and externalized configuration.
Setting Up Your Development Environment
Before we begin, make sure you have the following installed:
Java Development Kit (JDK): Spring Boot requires JDK 8 or later.
Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or Visual Studio Code.
Maven or Gradle: For dependency management.
Step 1: Initialize Your Spring Boot Project
You can quickly bootstrap a new Spring Boot project using Spring Initializr:
Open Spring Initializr.
Select the following options:
Project: Maven Project
Language: Java
Spring Boot: 2.7.18 (or the latest stable version)
Project Metadata: Group (e.g., com.example), Artifact (e.g., rest-api-demo)
Under "Dependencies", select:
Spring Web: For building web, including RESTful, applications using Spring MVC.
Click "Generate" to download the project as a ZIP file.
Unzip the file and open it in your preferred IDE.
pom file should have following parent and dependencies:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath />
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.91</version>
<scope>compile</scope>
</dependency>
Step 2: Create the Model
The model represents the data structure of your application. For this example, we’ll create a simple model class for Book.
package com.example.demo.model;
public class Book {
private Long id;
private String title;
private String author;
// Constructors, getters and setters
public Book() {}
public Book(Long id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
Step 3: Create the Rest Controller
The controller handles incoming HTTP requests and returns responses. Create a new controller class called BookController.
package com.example.demo.controller;
import com.example.demo.model.Book;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api/books")
public class BookController {
private List<Book> books = new ArrayList<>();
@GetMapping
public List<Book> getAllBooks() {
return books;
}
@GetMapping("/{id}")
public Book getBookById(@PathVariable Long id) {
return books.stream().filter(book -> book.getId().equals(id)).findFirst().orElse(null);
}
@PostMapping
public Book createBook(@RequestBody Book book) {
books.add(book);
return book;
}
@PutMapping("/{id}")
public Book updateBook(@PathVariable Long id, @RequestBody Book bookDetails) {
Book book = books.stream().filter(b -> b.getId().equals(id)).findFirst().orElse(null);
if (book != null) {
book.setTitle(bookDetails.getTitle());
book.setAuthor(bookDetails.getAuthor());
}
return book;
}
@DeleteMapping("/{id}")
public void deleteBook(@PathVariable Long id) {
books.removeIf(book -> book.getId().equals(id));
}
}
Step 4: Run Your Application
Spring Boot makes it easy to run your application. Simply run the main method in the RestApiDemoApplication class.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestApiDemoApplication {
public static void main(String[] args) {
SpringApplication.run(RestApiDemoApplication.class, args);
}
}
Step 5: Test Your API
You can use tools like Postman or cURL to test your API endpoints. Here are some example requests:
Get all books: GET http://localhost:8080/api/books
Get book by ID: GET http://localhost:8080/api/books/{id}
Create a new book: POST http://localhost:8080/api/books with JSON body:
{
"id": 1,
"title": "Spring Boot in Action",
"author": "Craig Walls"
}
Update a book: PUT http://localhost:8080/api/books/{id} with JSON body:
{
"title": "Spring Boot in Action, 2nd Edition",
"author": "Craig Walls"
}
Delete a book: DELETE http://localhost:8080/api/books/{id}
Conclusion
Congratulations! You have successfully created a simple REST API using Spring Boot. From here, you can explore more advanced features such as connecting to a database, adding security, and handling exceptions. Spring Boot's extensive documentation and vibrant community make it an excellent choice for building RESTful web services.
References
Get Involved! Share Your Feedback
Follow for more software architecture guides! Have suggestions? Share your thoughts on topics you’d like to see next.About Me
I am passionate about IT technologies. If you’re interested in learning more or staying updated with my latest articles, feel free to connect with me on:
Feel free to reach out through any of these platforms if you have any questions!
Comments
Post a Comment