Lecture 39: RESTful Web Services: Controllers, Request Mapping, CRUD APIs

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-27

Lecture 39

RESTful Web Services: Controllers, Request Mapping, CRUD APIs

Week 12 | Unit V: REST APIs
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Define REST and identify REST resource principles
  • Build REST controllers using Spring annotations
  • Use request mapping annotations for CRUD operations
  • Validate request data and return proper HTTP status codes
  • Design clean JSON response formats
  • Handle API exceptions centrally with @RestControllerAdvice

REST Principles


  • Resource-oriented URLs (/api/users/1)
  • HTTP methods define operation semantics
  • Stateless request handling
  • Representation via JSON (or XML)
  • Standard status codes for client-server contract

HTTP Methods and CRUD


HTTP Method CRUD Example Endpoint
GET Read /api/users , /api/users/{id}
POST Create /api/users
PUT Update (replace) /api/users/{id}
PATCH Partial update /api/users/{id}
DELETE Delete /api/users/{id}

REST Controller Example


@RestController
@RequestMapping("/api/users")
public class UserController {
  private final UserService service;
  public UserController(UserService service) { this.service = service; }

  @GetMapping
  public List<UserDto> getAll() { return service.findAll(); }

  @GetMapping("/{id}")
  public UserDto getById(@PathVariable Long id) { return service.findById(id); }

  @PostMapping
  @ResponseStatus(HttpStatus.CREATED)
  public UserDto create(@Valid @RequestBody UserCreateRequest req) {
    return service.create(req);
  }
}

Path Variables vs Query Parameters


@GetMapping("/{id}")
public UserDto byId(@PathVariable Long id) { ... }

@GetMapping
public List<UserDto> search(
  @RequestParam(required = false) String name,
  @RequestParam(defaultValue = "0") int page,
  @RequestParam(defaultValue = "10") int size
) { ... }

Use path variable for resource identity, query parameter for filtering/sorting/pagination.

Request Validation


public class UserCreateRequest {
  @NotBlank private String username;
  @Email private String email;
  @Size(min = 8, max = 20) private String password;
}

@PostMapping
public UserDto create(@Valid @RequestBody UserCreateRequest req) { ... }

Status Codes Best Practices


Scenario Status
Successful GET 200 OK
Successful POST create 201 Created
Successful DELETE no body 204 No Content
Invalid request payload 400 Bad Request
Resource not found 404 Not Found
Conflict (duplicate) 409 Conflict

Global Exception Handling


@RestControllerAdvice
public class ApiExceptionHandler {

  @ExceptionHandler(ResourceNotFoundException.class)
  public ResponseEntity<ApiError> notFound(ResourceNotFoundException ex) {
    return ResponseEntity.status(HttpStatus.NOT_FOUND)
      .body(new ApiError("NOT_FOUND", ex.getMessage()));
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  public ResponseEntity<ApiError> badRequest(...) { ... }
}

Consistent API Response Contract


{
  "success": true,
  "message": "User created",
  "data": {
    "id": 12,
    "username": "rahul"
  },
  "timestamp": 1775012000
}

Use a standard wrapper only if it helps consistency across all endpoints.

API Testing Checklist


  • Test happy path and failure path for each endpoint
  • Verify status code and JSON schema
  • Check validation messages for bad inputs
  • Verify pagination and filtering correctness
  • Use Postman/Insomnia and automated tests (MockMvc, WebTestClient)

Summary


  • REST API quality depends on clear contract and consistent semantics
  • Correct mappings + validation + status codes improve reliability
  • Global exception handling keeps controllers clean
  • Clean DTO-based API design is exam- and industry-ready

Questions?

Next: Lecture 40 - Spring Boot Actuator, Logger, Web App Build & Final Revision