Saturday, December 6, 2025

thumbnail

Creating REST APIs using Spring Boot

 Creating REST APIs Using Spring Boot


Spring Boot is one of the fastest and most popular ways to build RESTful APIs in Java.

It provides:


Auto-configuration


Embedded server (Tomcat/Jetty)


Minimal boilerplate


Production-ready features


With just a few annotations, you can build a fully working REST API.


✅ 1. Create a Spring Boot Project


Use Spring Initializr:


https://start.spring.io


Select:


Project: Maven or Gradle


Language: Java


Spring Boot: latest stable


Dependencies:


Spring Web


(Optional) Spring Data JPA


(Optional) H2 / MySQL Driver


(Optional) Lombok


Download the project and open it in IntelliJ/VS Code/Eclipse.


๐Ÿ 2. Application Entry Point


Spring Boot applications start with a class annotated with @SpringBootApplication:


@SpringBootApplication

public class ApiApplication {

    public static void main(String[] args) {

        SpringApplication.run(ApiApplication.class, args);

    }

}



Run the app—Spring Boot automatically starts an embedded Tomcat server on port 8080.


๐ŸŒ 3. Creating a REST Controller


A REST API endpoint is created using @RestController.


Example: Simple Controller

@RestController

@RequestMapping("/api/hello")

public class HelloController {


    @GetMapping

    public String sayHello() {

        return "Hello, Spring Boot REST API!";

    }

}



Visit:


➡ http://localhost:8080/api/hello


๐Ÿ“ฆ 4. Creating a Model (Entity or DTO)


Example domain object:


public class Product {

    private Long id;

    private String name;

    private double price;


    // getters and setters

}



Or use Lombok:


@Data

@AllArgsConstructor

@NoArgsConstructor

public class Product {

    private Long id;

    private String name;

    private double price;

}


๐Ÿง  5. Creating a Service Layer


Good practice: Keep controllers thin.


@Service

public class ProductService {


    private final List<Product> products = new ArrayList<>();


    public List<Product> getAll() {

        return products;

    }


    public Product getById(Long id) {

        return products.stream()

                .filter(p -> p.getId().equals(id))

                .findFirst()

                .orElseThrow(() -> new RuntimeException("Not Found"));

    }


    public Product create(Product product) {

        products.add(product);

        return product;

    }

}


๐Ÿ•น 6. Build CRUD REST Endpoints

@RestController

@RequestMapping("/api/products")

public class ProductController {


    private final ProductService service;


    public ProductController(ProductService service) {

        this.service = service;

    }


    @GetMapping

    public List<Product> getAll() {

        return service.getAll();

    }


    @GetMapping("/{id}")

    public Product getOne(@PathVariable Long id) {

        return service.getById(id);

    }


    @PostMapping

    public Product create(@RequestBody Product product) {

        return service.create(product);

    }

}


Test with Postman / curl:

curl -X POST http://localhost:8080/api/products \

     -H "Content-Type: application/json" \

     -d '{"id":1, "name":"Laptop", "price":1200.0}'


๐Ÿ—‚ 7. Adding Persistence (Optional but Common)


Add dependencies:


Spring Data JPA


H2 database


Create an Entity

@Entity

@Data

public class Product {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;


    private String name;

    private double price;

}


Create Repository

public interface ProductRepository extends JpaRepository<Product, Long> {

}


Update Service to Use Repository

@Service

public class ProductService {


    private final ProductRepository repo;


    public ProductService(ProductRepository repo) {

        this.repo = repo;

    }


    public List<Product> getAll() {

        return repo.findAll();

    }


    public Product getById(Long id) {

        return repo.findById(id)

                   .orElseThrow(() -> new RuntimeException("Not found"));

    }


    public Product create(Product product) {

        return repo.save(product);

    }

}



Now your API is fully persistent.


๐Ÿ›ก 8. Return Standard Responses (Best Practice)


Use ResponseEntity:


@GetMapping("/{id}")

public ResponseEntity<Product> getOne(@PathVariable Long id) {

    return ResponseEntity.ok(service.getById(id));

}


๐Ÿงช 9. Testing the API


You can test manually using:


Postman


curl


IntelliJ HTTP client


Swagger/OpenAPI (via Springdoc)


๐ŸŒŸ 10. Best Practices


✔ Use DTOs instead of exposing entities

✔ Validate input with @Valid + Bean Validation

✔ Use ResponseEntity for clear responses

✔ Implement exception handling with @ControllerAdvice

✔ Add Swagger for documentation

✔ Use layered architecture (Controller → Service → Repository)

✔ Use environment-based configuration (application.yml)


๐ŸŽ‰ Summary


To build REST APIs with Spring Boot:


Create a Spring Boot project


Add Spring Web dependency


Create a Controller


Create Models (DTOs/Entities)


Add a Service layer


Define CRUD endpoints


Optionally persist with Spring Data JPA


Test the endpoints


Spring Boot dramatically simplifies REST API development by providing auto-configuration, embedded servers, and easy-to-use annotations.

Learn Full Stack JAVA Course in Hyderabad

Read More

Spring Boot vs Spring MVC – Key Differences

What is Spring Framework? An Overview

Java Backend Architecture – MVC Explained

Introduction to Java Servlets

Visit Our Quality Thought Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive