RESTful API Development with Spring Boot

Certainly! Below is a comprehensive documentation on RESTful API Development with Spring Boot in Java, including example code.


📚 RESTful API Development with Spring Boot - Documentation

✅ Introduction

RESTful APIs (Representational State Transfer) allow communication between client and server using standard HTTP methods like GET, POST, PUT, and DELETE.

Spring Boot simplifies REST API development by providing:

  • Auto-configuration
  • Embedded server (Tomcat)
  • Easy integration with databases
  • Clean annotations for REST

✅ Project Setup

Use Spring Initializr (https://start.spring.io/) or Maven to create a project with the following dependencies:

  • Spring Web
  • Spring Data JPA (optional for database)
  • H2 Database / MySQL (optional)

✅ Example: RESTful API for Student Resource

📌 Directory Structure

src/main/java/com/example/demo/
│
├── controller/
│   └── StudentController.java
│
├── model/
│   └── Student.java
│
├── repository/
│   └── StudentRepository.java
│
└── DemoApplication.java

✅ Model Class - Student.java

package com.example.demo.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

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

    // Constructors
    public Student() {}
    public Student(String name, String course) {
        this.name = name;
        this.course = course;
    }

    // Getters and Setters
    // (Omitted for brevity)
}

✅ Repository - StudentRepository.java

package com.example.demo.repository;

import com.example.demo.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;

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

✅ Controller - StudentController.java

package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

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

    @Autowired
    private StudentRepository studentRepo;

    // GET all students
    @GetMapping
    public List<Student> getAllStudents() {
        return studentRepo.findAll();
    }

    // GET student by ID
    @GetMapping("/{id}")
    public Optional<Student> getStudentById(@PathVariable Long id) {
        return studentRepo.findById(id);
    }

    // POST - Add new student
    @PostMapping
    public Student createStudent(@RequestBody Student student) {
        return studentRepo.save(student);
    }

    // PUT - Update student
    @PutMapping("/{id}")
    public Student updateStudent(@PathVariable Long id, @RequestBody Student studentDetails) {
        Student student = studentRepo.findById(id).orElseThrow();
        student.setName(studentDetails.getName());
        student.setCourse(studentDetails.getCourse());
        return studentRepo.save(student);
    }

    // DELETE student
    @DeleteMapping("/{id}")
    public String deleteStudent(@PathVariable Long id) {
        studentRepo.deleteById(id);
        return "Student deleted with id: " + id;
    }
}

✅ Main Application - DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

✅ application.properties (H2 Database Example)

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

✅ Sample API Endpoints (Postman / Curl Example)

Method
Endpoint
Description
GET
/api/students
Fetch all students
GET
/api/students/{id}
Fetch student by ID
POST
/api/students
Add a new student
PUT
/api/students/{id}
Update existing student
DELETE
/api/students/{id}
Delete student by ID

✅ Sample JSON for POST/PUT

{
  "name": "John Doe",
  "course": "Computer Science"
}

✅ Example Test with cURL

# Create a student
curl -X POST -H "Content-Type: application/json" \
-d '{"name":"John Doe","course":"Math"}' \
http://localhost:8080/api/students

# Get all students
curl http://localhost:8080/api/students

✅ Benefits of Using Spring Boot for RESTful APIs

✔ Rapid development with embedded server

✔ Auto JSON serialization with Jackson

✔ Built-in Exception Handling

✔ Easy integration with databases

✔ Annotations make code clean and readable


✅ Next Enhancements (Optional)

  • Add global exception handling using @ControllerAdvice.
  • Use DTOs and ModelMapper for better structure.
  • Implement pagination and sorting.
  • Add Swagger/OpenAPI documentation.

✅ Conclusion

Spring Boot makes REST API development simple and powerful. With annotations like @RestController, @RequestMapping, and support for JSON, you can quickly build production-ready APIs.


Would you like me to generate a complete Maven pom.xml file, add Swagger documentation, or integrate a MySQL database example next?

Did this answer your question?
😞
😐
🤩