Create a RESTful API in Java with Spring Boot in Under 15 Minutes

Create a RESTful API in Java with Spring Boot in Under 15 Minutes

Create a RESTful API in Java with Spring Boot in Under 15 Minutes

 

Spring Boot has revolutionized Java development by simplifying the configuration and setup process. In this tutorial, we’ll show how to build a fully functional RESTful API in under 15 minutes using Spring Boot. You’ll create a project from scratch, define models, set up a controller, and handle real-world JSON data.

1. Setting Up a Spring Boot Project

We’ll use Spring Initializr to bootstrap our project.

  • Go to https://start.spring.io/
  • Project: Maven
  • Language: Java
  • Spring Boot: 3.0 or later
  • Dependencies: Spring Web, Lombok (optional), Spring Boot DevTools

Click Generate to download the project, unzip it, and open it in your IDE (e.g., IntelliJ IDEA or Eclipse).

2. Creating a Model Class

Let’s model a simple Book entity that represents book data in JSON format.

package com.example.demo.model;

public class Book {
    private Long id;
    private String title;
    private String author;

    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; }
}

This model class will be used to serialize and deserialize JSON data in requests and responses.

3. Creating the REST Controller

Now, write a BookController to define RESTful endpoints that allow clients to retrieve and add books.

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 final List<Book> bookList = new ArrayList<>();

    @GetMapping
    public List<Book> getAllBooks() {
        return bookList;
    }

    @PostMapping
    public Book addBook(@RequestBody Book book) {
        bookList.add(book);
        return book;
    }
}

This controller creates two endpoints:

  • GET /api/books: Returns a list of books.
  • POST /api/books: Accepts a JSON payload to add a book.

In a production app, you would use a database, but here we use an in-memory list for simplicity.

4. Testing with Postman or curl

Start your application by running DemoApplication.java. Now test the endpoints:

To fetch all books:

curl -X GET http://localhost:8080/api/books

To add a new book:

curl -X POST http://localhost:8080/api/books \
 -H "Content-Type: application/json" \
 -d '{"id":1, "title":"The Pragmatic Programmer", "author":"Andy Hunt"}'

Responses will be served in JSON format automatically, thanks to Spring Boot’s built-in Jackson support.

5. Enhancements and Best Practices

To go beyond the basics and write maintainable, testable APIs, consider the following:

  • Use DTOs: Avoid exposing internal models directly. Create Data Transfer Objects to encapsulate data.
  • Add Validation: Use annotations like @NotNull and @Size and add @Valid to your controller parameters.
  • Use a Database: Swap the list with Spring Data JPA and connect to an H2, MySQL, or PostgreSQL database.
  • Error Handling: Use @ControllerAdvice to return clean, consistent error messages.
  • Document with Swagger: Add springdoc-openapi-ui for auto-generated API documentation endpoints.
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.0.0</version>
</dependency>

Now, visiting http://localhost:8080/swagger-ui/index.html will show your API UI.

Conclusion

With Spring Boot, setting up a RESTful API in Java is fast, clean, and scalable. In under 15 minutes, you created a working API that handles JSON requests — perfect for beginners or as a base for more complex systems. Start small, keep it modular, and build on with good practices like persistence, testing, and documentation.

 

Useful links:

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *