DAY-36
Building a Simple Spring Boot REST API
Tutor Mentor| 2024
1
What is a REST API?
Definition: REST API (Representational State Transfer API) allows clients to
communicate with servers via stateless HTTP methods such as GET, POST, PUT, and
DELETE.
Purpose: To expose application functionality to external systems in a structured way.
Tutor Mentor | 2024
2
Why Spring Boot for REST APIs?
Advantages:
Simplifies RESTful API development with built-in support for annotations like
@RestController.
Provides tools for HTTP method mapping, data handling, and error management.
Easy database integration using Spring Data JPA.
Tutor Mentor | 2024
3
Overview of REST API Layers
Controller Layer: Handles HTTP requests and directs them to appropriate services.
Service Layer: Contains business logic, acting as a bridge between the controller and
the repository.
Repository Layer: Manages database operations and data retrieval.
Tutor Mentor | 2024
4
Creating a Spring Boot Project
Steps:
1. Go to Spring Initializr.
2. Add dependencies: Spring Web, Spring Data JPA, H2 Database.
3. Generate the project and import it into an IDE like IntelliJ or STS
Tutor Mentor | 2024
5
Understanding Spring Boot Project Structure
Folders:
src/main/java: Contains controllers, services, and other Java classes.
src/main/resources: Contains configuration files like application.properties.
Key Class
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Tutor Mentor | 2024
6
Creating a Controller
Purpose: Handles incoming HTTP requests and maps them to corresponding endpoints.
Example:
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService service;
@GetMapping
public List<Product> getAllProducts() {
return service.getAllProducts();
} Tutor Mentor | 2024
7
@PostMapping
public Product addProduct(@RequestBody Product product) {
return service.saveProduct(product);
}
}
Tutor Mentor | 2024
8
Understanding Request Mappings
Key Annotations:
@RestController: Marks the class as a REST controller.
@RequestMapping: Specifies the base URL for endpoints.
HTTP Method Annotations:
@GetMapping: Maps GET requests.
@PostMapping: Maps POST requests.
@PutMapping: Maps PUT requests.
@DeleteMapping: Maps DELETE requests.
Tutor Mentor | 2024
9
Creating a Service Layer
Role: Contains business logic and bridges the controller and repository.
Example:
@Service
public class ProductService {
@Autowired
private ProductRepository repository;
public List<Product> getAllProducts() {
return repository.findAll();
} public Product saveProduct(Product product) {
return repository.save(product); } }
Tutor Mentor | 2024
10
What is Spring Data JPA?
Definition: Spring Data JPA simplifies database interaction using the Java Persistence API.
Features:
Auto-implemented repositories.
Reduced boilerplate code.
Tutor Mentor | 2024
11
Creating a Repository
Definition: Manages direct database operations.
Example:
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Tutor Mentor | 2024
12
Defining the Product Entity
Purpose: Maps Java objects to database tables.
Example:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and Setters }
Tutor Mentor | 2024
13
Configuring the Database
File: application.properties
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
Tutor Mentor | 2024
14
Testing Endpoints - GET Request
Endpoint: /api/products
Method: GET
Tool: Use Postman or cURL to test the API.
Tutor Mentor | 2024
15
Testing Endpoints - POST Request
Endpoint: /api/products
Method: POST
Payload:
{
"name": "Laptop",
"price": 50000
}
Response: Returns the created product object.
Tutor Mentor | 2024
16
Application Flow
Client: Sends POST request to /api/products.
Controller: Handles the request.
Service Layer: Applies business logic.
Repository: Interacts with the database.
Response: Returns saved product.
Tutor Mentor | 2024
17
Testing the Complete Flow
Manual Testing: Use Postman.
Automated Testing:
Write unit tests using JUnit and MockMvc.
Example
@Test
public void testGetAllProducts() throws Exception {
mockMvc.perform(get("/api/products"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)));
}
Tutor Mentor | 2024
18
Common Errors and Debugging Tips
Errors:
404 Not Found: Incorrect endpoint.
500 Internal Server Error: Code exception.
400 Bad Request: Invalid input payload.
Debugging: Enable detailed logs in application.properties:
logging.level.org.springframework=DEBUG
Tutor Mentor | 2024
19
Real-World Use Case
Scenario: Building an e-commerce platform with REST endpoints for:
Products: CRUD operations.
Users: Authentication and profile management.
Tutor Mentor | 2024
20
Summary
REST API layers: Controller, Service, Repository.
Key annotations: @RestController, @Service, @Repository.
Tools like Spring Boot, Postman, and Spring Data JPA simplify development and testing.
Tutor Mentor | 2024
Tutor Mentor | 2024
THANK YOU
Ask Me Anything!