Spring Boot Tutorial: A Beginner’s Guide to Building RESTful Applications

Spring Boot Tutorial: A Beginner’s Guide to Building RESTful Applications

In today’s world of web and mobile applications, most systems rely on APIs (Application Programming Interfaces) to communicate with each other. One of the most popular ways of building APIs is using REST (Representational State Transfer), and Java developers often choose Spring Boot Tutorial for this purpose.

Spring Boot simplifies the process of developing robust, production-ready applications with minimal effort. In this tutorial, we will cover what Spring Boot is, why it’s widely used, how to set it up, and how to build a simple RESTful API step by step.

What is Spring Boot?

Spring Boot is a framework built on top of the Spring Framework, designed to make application development faster and easier. It eliminates the need for complex configurations and boilerplate code, providing developers with a simple, opinionated setup to get started quickly.

Key Features of Spring Boot

  1. Auto-configuration – Automatically configures components based on project dependencies.

  2. Embedded Servers – Comes with Tomcat, Jetty, or Undertow built-in, so no need to deploy WAR files.

  3. Production-ready Tools – Includes health checks, metrics, and monitoring features.

  4. Starter Dependencies – Provides pre-defined dependency sets to speed up development.

  5. Minimal Configuration – Focus more on business logic and less on XML configuration.

Why Use Spring Boot for RESTful APIs?

  1. Rapid Development – Quick setup and minimal configuration.

  2. Scalability – Suitable for small apps and enterprise-grade applications.

  3. Integration – Works seamlessly with databases, security modules, and cloud platforms.

  4. Community Support – Large community and documentation available.

  5. Ease of Testing – Built-in support for unit and integration testing.

Setting Up a Spring Boot Project

You can set up a Spring Boot project in multiple ways:

1. Using Spring Initializr (Recommended)

Go to start.spring.io and choose:

  • Project: Maven or Gradle

  • Language: Java

  • Spring Boot version: Latest stable release

  • Dependencies: Spring Web, Spring Data JPA, H2 Database (optional), Spring Boot DevTools

Click Generate, and you’ll get a ZIP file with the project structure.

2. Using IDE Plugins

If you’re using IntelliJ IDEA, Eclipse, or STS, they provide built-in wizards for Spring Boot projects.

Project Structure Overview

Once you generate the project, it will have a structure like this:

src/main/java/com/example/demo
    └── DemoApplication.java
src/main/resources
    ├── application.properties
    └── static/
    └── templates/
  • DemoApplication.java – The main class with the @SpringBootApplication annotation.

  • application.properties – Used for configurations like database setup and server port.

  • static/templates – For serving static files and templates if needed.

Creating a Simple REST API with Spring Boot

Let’s build a simple Student Management REST API.

Step 1: Create a Model Class

package com.example.demo.model;

public class Student {
    private int id;
    private String name;
    private int age;

    // Constructor
    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    // Getters and setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

Step 2: Create a REST Controller

package com.example.demo.controller;

import com.example.demo.model.Student;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/students")
public class StudentController {

    private List<Student> students = new ArrayList<>();

    // Sample data
    public StudentController() {
        students.add(new Student(1, "Alice", 20));
        students.add(new Student(2, "Bob", 22));
    }

    // Get all students
    @GetMapping
    public List<Student> getAllStudents() {
        return students;
    }

    // Get student by ID
    @GetMapping("/{id}")
    public Student getStudentById(@PathVariable int id) {
        return students.stream()
                .filter(s -> s.getId() == id)
                .findFirst()
                .orElse(null);
    }

    // Add a new student
    @PostMapping
    public Student addStudent(@RequestBody Student student) {
        students.add(student);
        return student;
    }

    // Update student
    @PutMapping("/{id}")
    public Student updateStudent(@PathVariable int id, @RequestBody Student updatedStudent) {
        for (Student s : students) {
            if (s.getId() == id) {
                s.setName(updatedStudent.getName());
                s.setAge(updatedStudent.getAge());
                return s;
            }
        }
        return null;
    }

    // Delete student
    @DeleteMapping("/{id}")
    public String deleteStudent(@PathVariable int id) {
        students.removeIf(s -> s.getId() == id);
        return "Student removed successfully!";
    }
}

Step 3: Run the Application

Run the application from your IDE or using the command:

mvn spring-boot:run

The server will start at http://localhost:8080/.

Step 4: Test the API

Use Postman or curl to test endpoints:

  • GET /students → Retrieve all students

  • GET /students/1 → Get student with ID 1

  • POST /students → Add a new student

  • PUT /students/1 → Update student with ID 1

  • DELETE /students/1 → Delete student with ID 1

Working with Database (Optional)

Instead of using in-memory data, you can connect to a database like H2, MySQL, or PostgreSQL.

Example: H2 Database Configuration

Add the dependency in pom.xml:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

Configure in application.properties:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

You can now access the H2 console at http://localhost:8080/h2-console.

Advantages of Using Spring Boot for REST APIs

  1. Rapid Development – Faster project setup and less boilerplate.

  2. Scalability – Handles both small and enterprise applications.

  3. Microservices Friendly – Ideal for building microservices-based architectures.

  4. Integration – Works well with databases, cloud, and third-party APIs.

  5. Community & Ecosystem – Large ecosystem with Spring Security, Spring Data, and Spring Cloud.

Best Practices for REST APIs in Spring Boot

  1. Use Proper HTTP Status Codes200 OK, 201 Created, 404 Not Found, etc.

  2. Exception Handling – Use @ControllerAdvice for centralized error handling.

  3. Validation – Use @Valid and @NotNull annotations for request validation.

  4. Pagination – Implement pagination for large datasets.

  5. Security – Use Spring Security for authentication and authorization.

Conclusion

Spring Boot makes building RESTful applications simple, efficient, and production-ready. With minimal setup, you can create a REST API, connect it to a database, and deploy it with ease.

In this tutorial, we covered:

  • What Spring Boot is and why it’s useful.

  • How to set up a Spring Boot project.

  • Creating a REST controller for CRUD operations.

  • Connecting with a database (H2).

  • Best practices for building APIs.

Whether you are a beginner in Java development or looking to enhance your skills in building scalable web services, Spring Boot Tutorial is a must-learn framework. Start experimenting with small projects, and gradually move on to more advanced concepts like Spring Data JPA, Spring Security, and Spring Cloud for microservices.




Comments

Popular posts from this blog

Quantitative Aptitude Questions and Answers with Solutions for Beginners

Java Tutorial: Master Object-Oriented Programming

Exception Handling in Java: Try, Catch, and Throw