How to Build a Simple REST API with Spring Boot: A Step-by-Step Guide


Spring Boot is a java framework , that makes developers life easy by simplifying the process of creating and running java application especially web applications. It provides preconfigured dependencies , auto configuration and other features that reduces complexity and time to develop the application.
Today we will learn to build a simple REST API with spring boot and will test it. So let’s get started without further ado.
Step 0: Create a Spring Boot project using Spring Initializr.
To start building a Spring Boot project, go to Spring Initializr, select Maven as the project type, and use Spring Boot version 3.4.5. Set the project metadata with the group as com.example
, artifact as myfirstproject
, and other details. Add dependencies like Spring Web and optionally Lombok. Download the project as a Zip file, unzip it, and import it into your Java IDE as a Maven project. Wait for the IDE to set up the project, and you're ready to begin.
Step 1: Create a Model class.
public class Book {
private Long id;
private String title;
private String author;
//Create Constructors and Getter and Setter (If you didnt add Lombok dependency)
// Constructors
public Book() {}
public Book(Long id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
// Getters and setters
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 2 : Create Rest Controller
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
private List<Book> books = new ArrayList<>();
@GetMapping
public List<Book> getAllBooks() {
return books;
}
@PostMapping
public Book addBook(@RequestBody Book book) {
books.add(book);
return book;
}
}
Step 3: Run Your Application
Run the main class annotated with @SpringBootApplication. Your application will start at port http://localhost:8080.
Step 4: Use Postman to test your applocation.
Get All Books : GET http://localhost:8080/books
Add a new book : POST http://localhost:8080/books
Body (JSON):
{
"id": 1,
"title": "Clean Code",
"author": "Robert C. Martin"
}
Conclusion:
You just created a basic REST API using Spring Boot! Next, you can extend this by adding database support, validation, or security.
Hope this article help you to create your first spring boot application .
Thank You. See you next time . Happy Learning !!!
Subscribe to my newsletter
Read articles from Aritra Sarkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
