Module 4: RESTful API Design (Java)
This module introduces the principles of RESTful API design and implementation using Java-based frameworks such as Spring Boot. Students will learn how to create, document, and test APIs that allow seamless communication between client and server.
4.1 Learning Objectives
- Understand the fundamentals of REST architecture and HTTP methods.
- Design and implement RESTful APIs using Spring Boot.
- Handle routing, request mapping, and parameter passing.
- Document APIs using OpenAPI/Swagger.
- Test endpoints using Postman and JUnit.
4.2 Key Concepts
- REST Principles: Statelessness, client-server separation, layered system, cacheability.
- HTTP Methods: GET, POST, PUT, DELETE, PATCH.
- HTTP Status Codes: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error.
- URI Design: Best practices for naming and structuring endpoints.
4.3 Setting Up Spring Boot
- Install Java JDK and Maven.
- Create a new Spring Boot project using Spring Initializr.
- Select dependencies: Spring Web, Spring Boot DevTools, Lombok.
- Build and run the application using
mvn spring-boot:run.
4.4 Creating a Simple REST API
package com.example.demo.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
@PostMapping("/greet")
public String greetUser(@RequestBody String name) {
return "Hello, " + name + "!";
}
}
4.5 Using Postman for Testing
Use Postman or cURL to send HTTP requests and test your endpoints. Verify responses, status codes, and data formatting.
4.6 Documenting APIs
Use Swagger (OpenAPI 3.0) for auto-generating API documentation.
Add the dependency to your pom.xml and access docs at http://localhost:8080/swagger-ui.html.
4.7 Exercise
- Develop a simple CRUD API for a
Studententity (create, read, update, delete). - Include error handling and validation for missing fields.
- Test your API using Postman.