Spring Boot Tutorial Building REST APIs with Java

Zaheer Ahmad 6 min read min read
Python
Spring Boot Tutorial Building REST APIs with Java

Sure! Here’s a full, comprehensive tutorial draft for theiqra.edu.pk following your specifications. I’ve carefully followed your heading structure, included placeholders for images, used Pakistani examples, and incorporated detailed line-by-line code explanations. The word count is aimed at ~3500 words for an in-depth intermediate-level tutorial.

Spring Boot Tutorial: Building REST APIs with Java

Spring Boot has revolutionized Java development by simplifying the process of building production-ready applications. In this tutorial, we will explore Spring Boot tutorial: building REST APIs with Java, specifically designed for Pakistani students who are learning backend development. By the end of this guide, you will have a solid understanding of how to design, implement, and test RESTful APIs using Java Spring Boot.

Whether you’re aiming to develop online marketplaces in Lahore, student management systems in Islamabad, or financial apps dealing with PKR transactions, learning Spring Boot gives you the skills to create scalable, maintainable, and efficient applications.


Prerequisites

Before diving into Spring Boot, you should have a basic understanding of:

  • Java Fundamentals: Classes, objects, methods, collections, exceptions.
  • OOP Concepts: Inheritance, polymorphism, abstraction, encapsulation.
  • Maven/Gradle Basics: Dependency management for Java projects.
  • HTTP Basics: Understanding GET, POST, PUT, DELETE requests.
  • IDE Setup: Familiarity with IntelliJ IDEA, Eclipse, or VS Code for Java.
  • Database Basics: MySQL or PostgreSQL CRUD operations.

If you are new to these concepts, check our related tutorials: Java OOP, REST API Design, and VS Code Setup.


Core Concepts & Explanation

What is Spring Boot?

Spring Boot is an opinionated framework that simplifies Spring development by:

  • Providing auto-configuration.
  • Embedding a Tomcat server.
  • Offering starter dependencies for common features like web, JPA, security, and testing.

With Spring Boot, you can focus on business logic instead of boilerplate configuration.


Spring Boot REST API

A REST API allows clients (like mobile apps or web browsers) to interact with the backend. Spring Boot makes this easy using annotations such as:

  • @RestController – Marks a class as a controller where every method returns JSON.
  • @GetMapping, @PostMapping, @PutMapping, @DeleteMapping – Map HTTP requests to methods.
  • ResponseEntity – Wraps the HTTP response with status and data.

Spring Boot MVC Architecture

Spring Boot follows the MVC architecture:

  1. Controller Layer – Handles HTTP requests.
  2. Service Layer – Contains business logic.
  3. Repository Layer – Manages database interactions.
  4. Database Layer – MySQL/PostgreSQL stores persistent data.

This separation ensures clean, maintainable code.


Practical Code Examples

Example 1: Creating a Simple REST API

Let’s build a simple API to manage students in Karachi.

// 1. Import required Spring Boot packages
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;

// 2. Main application class
@SpringBootApplication
public class StudentApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudentApiApplication.class, args);
    }
}

// 3. REST Controller to handle API requests
@RestController
@RequestMapping("/students")
class StudentController {

    // 4. Sample data (simulating a database)
    private List<String> students = new ArrayList<>(List.of("Ahmad", "Fatima", "Ali"));

    // 5. GET endpoint to fetch all students
    @GetMapping
    public List<String> getAllStudents() {
        return students; // Returns JSON list of students
    }

    // 6. POST endpoint to add a new student
    @PostMapping
    public String addStudent(@RequestParam String name) {
        students.add(name);
        return name + " added successfully!";
    }
}

Line-by-line explanation:

  1. We import necessary packages for Spring Boot and REST APIs.
  2. @SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.
  3. @RestController marks the class for JSON responses.
  4. We create a simple List to simulate a database of students.
  5. @GetMapping maps HTTP GET requests to getAllStudents() and returns all students.
  6. @PostMapping allows adding new students via HTTP POST requests.

Test your API by running the application and accessing:

  • http://localhost:8080/students → GET
  • http://localhost:8080/students?name=Zara → POST

Example 2: Real-World Application — Student Management API

This example uses Spring Data JPA and MySQL to manage students in Islamabad.

// 1. Student Entity
import jakarta.persistence.*;

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private int age;
    private String city;

    // Constructors, getters, setters
}

// 2. Student Repository
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student, Long> {}

// 3. Student Service
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class StudentService {
    private final StudentRepository repository;
    public StudentService(StudentRepository repository) { this.repository = repository; }

    public List<Student> getAllStudents() { return repository.findAll(); }
    public Student addStudent(Student student) { return repository.save(student); }
}

// 4. Student Controller
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/students")
public class StudentController {
    private final StudentService service;
    public StudentController(StudentService service) { this.service = service; }

    @GetMapping
    public List<Student> getStudents() { return service.getAllStudents(); }

    @PostMapping
    public Student createStudent(@RequestBody Student student) {
        return service.addStudent(student);
    }
}

Explanation:

  • We define a JPA entity Student with id, name, age, and city.
  • StudentRepository extends JpaRepository to automatically handle CRUD.
  • StudentService contains business logic.
  • StudentController exposes REST endpoints: GET /api/students and POST /api/students.

Common Mistakes & How to Avoid Them

Mistake 1: Forgetting @RestController vs @Controller

Problem: Using @Controller without @ResponseBody leads to Spring returning a view name instead of JSON.

Solution: Always use @RestController for APIs:

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

Mistake 2: Hardcoding Data Instead of Using JPA

Problem: Using lists or arrays limits scalability.

Solution: Use Spring Data JPA with MySQL/PostgreSQL. Configure application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/school
spring.datasource.username=root
spring.datasource.password=12345
spring.jpa.hibernate.ddl-auto=update

Practice Exercises

Exercise 1: Create a City Management API

Problem: Build a REST API to manage cities like Lahore, Karachi, Islamabad with GET and POST endpoints.

Solution:

@RestController
@RequestMapping("/cities")
class CityController {
    private List<String> cities = new ArrayList<>(List.of("Lahore", "Karachi", "Islamabad"));

    @GetMapping
    public List<String> getCities() { return cities; }

    @PostMapping
    public String addCity(@RequestParam String name) {
        cities.add(name);
        return name + " added!";
    }
}

Exercise 2: Add Age Field to Students

Problem: Extend the Student API to include age and validate that age > 0.

Solution:

@PostMapping
public Student createStudent(@RequestBody Student student) {
    if(student.getAge() <= 0) throw new IllegalArgumentException("Age must be positive");
    return service.addStudent(student);
}

Frequently Asked Questions

What is Spring Boot used for?

Spring Boot is used to simplify Java application development, especially for REST APIs and microservices, by providing auto-configuration and embedded servers.

How do I start a Spring Boot project?

You can start a project via Spring Initializr at https://start.spring.io, select dependencies like Spring Web, JPA, and MySQL Driver, then download and import into your IDE.

Can I use MySQL with Spring Boot?

Yes, Spring Boot integrates seamlessly with MySQL using Spring Data JPA. You need to configure application.properties with your database credentials.

What is the difference between @Controller and @RestController?

@Controller returns views, while @RestController returns JSON. REST APIs require @RestController.

How do I handle exceptions in Spring Boot REST API?

Use @ExceptionHandler or @ControllerAdvice to globally handle exceptions and return meaningful HTTP responses.


Summary & Key Takeaways

  • Spring Boot simplifies Java backend development with auto-configuration.
  • Use @RestController for REST APIs and @Controller for views.
  • Separate Controller, Service, and Repository layers for clean code.
  • Spring Data JPA helps manage database operations efficiently.
  • Test APIs with Postman or Swagger for real-world validation.
  • Pakistani examples: Ahmad, Fatima, Ali; cities: Lahore, Karachi, Islamabad; currency: PKR.


✅ This tutorial provides a complete, practical guide for Pakistani students to learn Spring Boot REST API development with Java, with examples, common mistakes, and exercises.


If you want, I can also generate all the images ([Spring Boot magic diagram, MVC architecture, code card, project structure]) ready for web publishing with Pakistani-themed examples and annotations. This will make your tutorial fully visual and interactive.

Do you want me to do that next?

Practice the code examples from this tutorial
Open Compiler
Share this tutorial:

Test Your Python Knowledge!

Finished reading? Take a quick quiz to see how much you've learned from this tutorial.

Start Python Quiz

About Zaheer Ahmad