Lesson 35 • Advanced

    REST APIs with Java

    REST APIs are how modern apps communicate. Whether it's a mobile app talking to a backend, or microservices talking to each other, Spring Boot makes building production-quality REST APIs surprisingly straightforward. This is one of the most marketable Java skills you can have.

    Before You Start

    You should know Annotations (Spring is annotation-driven) and JDBC (data layer). Understanding HTTP methods (GET, POST, PUT, DELETE) and JSON is essential.

    What You'll Learn

    • ✅ REST principles: resources, HTTP methods, status codes
    • ✅ Spring Boot @RestController and @RequestMapping
    • ✅ Path variables, query parameters, request bodies
    • ✅ Response entities and proper HTTP status codes
    • ✅ Input validation with @Valid and Bean Validation
    • ✅ Global exception handling with @ControllerAdvice

    1️⃣ REST Design Principles

    Analogy: Think of a REST API like a restaurant menu. Each endpoint is a menu item (resource). You use different HTTP methods to interact: GET (read the menu), POST (place an order), PUT (change your order), DELETE (cancel). The waiter (server) responds with a status code — 200 (here's your food), 404 (we don't serve that), 500 (kitchen exploded).

    MethodEndpointActionStatus
    GET/api/usersList all users200 OK
    GET/api/users/42Get user #42200 / 404
    POST/api/usersCreate user201 Created
    PUT/api/users/42Replace user200 OK
    DELETE/api/users/42Delete user204 No Content

    Try It: REST API Request Router

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Build a mini REST API router (simulating Spring Boot)
    
    console.log("=== REST API Request Router ===\n");
    
    // In-memory database
    let users = [
      { id: 1, name: "Alice", email: "alice@test.com" },
      { id: 2, name: "Bob", email: "bob@test.com" },
    ];
    let nextId = 3;
    
    // REST Controller (simulating @RestController)
    function handleRequest(method, path, body) {
      let match;
      
      // GET /api/users
      if (method === "GET" && path === "/api/users") {
     
    ...

    2️⃣ Input Validation & Error Handling

    Never trust client input. Spring Boot's @Valid annotation with Bean Validation annotations automatically rejects malformed requests with a 400 status code. Combine with @ControllerAdvice for consistent error responses across your entire API.

    @NotBlank — field must not be null or empty

    @Email — must be a valid email format

    @Min(0) @Max(150) — numeric range validation

    @Size(min=2, max=50) — string length constraints

    Try It: Validation & Error Handling

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Input validation and global error handling simulation
    
    console.log("=== Validation & Error Handling ===\n");
    
    // Validation rules (simulating Bean Validation annotations)
    const validationRules = {
      name: { required: true, minLength: 2, maxLength: 50 },
      email: { required: true, pattern: /^[^@]+@[^@]+\.[^@]+$/ },
      age: { min: 0, max: 150 },
    };
    
    function validate(data) {
      let errors = [];
      
      // @NotBlank name
      if (!data.name || data.nam
    ...

    Common Mistakes

    • ⚠️ Using verbs in URLs: /api/getUser is wrong — use GET /api/users/42
    • ⚠️ Always returning 200: Use proper status codes — 201 for creation, 204 for deletion, 400 for bad input
    • ⚠️ Exposing entities directly: Use DTOs to control what data reaches the client
    • ⚠️ No input validation: Always use @Valid — never trust client input

    Pro Tips

    • 💡 Use @ControllerAdvice for global exception handling — one place for all error responses
    • 💡 ResponseEntity<T> gives you full control over headers and status codes
    • 💡 Use pagination for list endpoints: ?page=0&size=20&sort=name,asc
    • 💡 Version your API: /api/v1/users — don't break existing clients

    Try It: Full REST API with Pagination

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Full REST API with pagination and filtering
    
    console.log("=== REST API with Pagination ===\n");
    
    // Generate sample data
    let products = [];
    for (let i = 1; i <= 50; i++) {
      products.push({
        id: i,
        name: "Product " + i,
        category: ["Electronics", "Books", "Clothing"][i % 3],
        price: Math.round(Math.random() * 200 + 10),
      });
    }
    console.log("Database: " + products.length + " products\n");
    
    // Paginated endpoint: GET /api/products
    ...

    📋 Quick Reference

    AnnotationPurposeExample
    @RestControllerREST controller classReturns JSON by default
    @GetMappingHandle GET requests@GetMapping("/{id}")
    @RequestBodyDeserialize JSON bodyPOST/PUT payloads
    @PathVariableURL path parameter/users/{id}
    @ValidTrigger validationBean Validation checks

    🎉 Lesson Complete!

    You can now build production-quality REST APIs with Java and Spring Boot! Next: JSON & XML — serialization and data interchange formats.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service