Creating REST APIs using Spring Boot
Creating REST APIs Using Spring Boot
Spring Boot is a popular framework for building production-ready REST APIs in Java with minimal setup. It simplifies the development process by providing auto-configuration and a variety of tools to quickly build robust backend applications.
✅ Prerequisites
Java 17+ installed
Maven or Gradle installed
IDE (e.g., IntelliJ IDEA, Eclipse, VS Code)
Spring Boot CLI (optional)
1. Create a Spring Boot Project
You can use Spring Initializr to generate a project:
๐ง Choose:
Project: Maven or Gradle
Language: Java
Spring Boot version: (latest stable)
Dependencies:
Spring Web
Spring Boot DevTools (optional)
Spring Data JPA (if using a database)
H2 Database (for quick testing)
Click Generate, then unzip and open the project in your IDE.
2. Define a Model Class
Create a simple class to represent your data.
java
Copy
Edit
// src/main/java/com/example/demo/model/Product.java
package com.example.demo.model;
public class Product {
private Long id;
private String name;
private double price;
// Getters and setters
}
3. Create a REST Controller
Define endpoints to handle HTTP requests.
java
Copy
Edit
// src/main/java/com/example/demo/controller/ProductController.java
package com.example.demo.controller;
import com.example.demo.model.Product;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/api/products")
public class ProductController {
private Map<Long, Product> productDB = new HashMap<>();
private Long nextId = 1L;
@GetMapping
public List<Product> getAllProducts() {
return new ArrayList<>(productDB.values());
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productDB.get(id);
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
product.setId(nextId++);
productDB.put(product.getId(), product);
return product;
}
@PutMapping("/{id}")
public Product updateProduct(@PathVariable Long id, @RequestBody Product updatedProduct) {
updatedProduct.setId(id);
productDB.put(id, updatedProduct);
return updatedProduct;
}
@DeleteMapping("/{id}")
public String deleteProduct(@PathVariable Long id) {
productDB.remove(id);
return "Product deleted successfully";
}
}
4. Run the Application
In your IDE or using the command line:
bash
Copy
Edit
./mvnw spring-boot:run
or
bash
Copy
Edit
gradle bootRun
Default server port: http://localhost:8080
5. Test Your API
You can use tools like:
Postman
curl
httpie
Browser (for GET requests)
Example curl requests:
bash
Copy
Edit
curl -X POST http://localhost:8080/api/products \
-H "Content-Type: application/json" \
-d '{"name":"Laptop", "price":999.99}'
curl http://localhost:8080/api/products
6. (Optional) Use Spring Data JPA for Persistence
Add a JPA entity:
java
Copy
Edit
@Entity
public class Product {
@Id @GeneratedValue
private Long id;
private String name;
private double price;
// getters and setters
}
Create a repository:
java
Copy
Edit
public interface ProductRepository extends JpaRepository<Product, Long> {}
Update your controller:
java
Copy
Edit
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductRepository repo;
@GetMapping
public List<Product> getAll() { return repo.findAll(); }
@PostMapping
public Product create(@RequestBody Product product) { return repo.save(product); }
@PutMapping("/{id}")
public Product update(@PathVariable Long id, @RequestBody Product p) {
p.setId(id);
return repo.save(p);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) { repo.deleteById(id); }
}
✅ Conclusion
With Spring Boot, creating REST APIs is simple and efficient. You can start with in-memory storage for learning, then scale to full database-backed APIs using JPA.
➕ Next Steps
Add input validation with @Valid
Secure your API with Spring Security + JWT
Add exception handling with @ControllerAdvice
Generate OpenAPI docs using Springdoc or Swagger
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
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment