REST APIs Made Simple: Build a Mini API in Java

REST APIs Made Simple: Build a Mini API in Java

REST APIs Made Simple: Build a Mini API in Java

 

Introduction

REST APIs have become the backbone of modern web applications, enabling communication between systems in a standardized, stateless way. In this post, we’ll simplify how to build a mini RESTful API in Java using Spring Boot. You’ll learn how to set up a simple project, define GET and POST routes, and return JSON responses—all in under 100 lines of code. By the end, you’ll have a working REST API ready to serve data or integrate with frontends.

1. Setting Up the Project

Before writing code, let’s quickly scaffold our Spring Boot application. The easiest way is to use Spring Initializr. Choose the following options:

  • Project: Maven
  • Language: Java
  • Spring Boot: Latest Stable
  • Dependencies: Spring Web

Once downloaded, unzip and open the project in your IDE (like IntelliJ IDEA or VS Code with Java extensions). The generated project structure will contain a src/main/java folder with a main class.

Here’s what the entry point looks like:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

This simple class bootstraps a lightweight web server (embedded Tomcat) and automatically configures your application using Spring Boot’s auto-configuration magic.

2. Creating a Basic Controller

Controllers in Spring handle HTTP requests. Let’s create one that will respond to simple GET requests.

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {

    @GetMapping("/api/hello")
    public Map<String, String> sayHello() {
        Map<String, String> response = new HashMap<>();
        response.put("message", "Hello from your Java REST API!");
        return response;
    }
}

When you run the application and visit http://localhost:8080/api/hello in your browser, you should see a JSON response like:

{
  "message": "Hello from your Java REST API!"
}

Spring automatically serializes your Java Map into JSON. Easy and powerful.

3. Adding a POST Endpoint

Next, let’s create a POST route to accept JSON data. This is where we handle user input or data creation.

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {

    @PostMapping("/user")
    public Map<String, Object> createUser(@RequestBody Map<String, Object> userData) {
        // Here you can integrate with a database or service
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("data", userData);
        response.put("message", "User created successfully!");
        return response;
    }
}

Test it with curl or a REST tool like Postman:

curl -X POST -H "Content-Type: application/json" -d '{"name": "Alice", "age": 28}' http://localhost:8080/api/user

Expected response:

{
  "status": "success",
  "data": {"name": "Alice", "age": 28},
  "message": "User created successfully!"
}

4. Structuring Your Application for Growth

As your API grows, good structure matters. Let’s separate logic from controllers by using a Service Layer. This improves maintainability and testing.

package com.example.demo.service;

import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.HashMap;

@Service
public class UserService {
    public Map<String, Object> processUser(Map<String, Object> input) {
        Map<String, Object> result = new HashMap<>();
        result.put("confirmationId", System.currentTimeMillis());
        result.put("user", input);
        return result;
    }
}

And in your UserController:

@RestController
@RequestMapping("/api")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/user")
    public Map<String, Object> createUser(@RequestBody Map<String, Object> userData) {
        return userService.processUser(userData);
    }
}

This pattern ensures clear separation of concerns—controllers deal with HTTP, while services handle business logic.

5. Best Practices and Performance Tips

To keep your REST API efficient and maintainable, consider the following best practices:

  • Use DTOs (Data Transfer Objects): Instead of maps, define typed POJOs for requests and responses for compile-time safety and clarity.
  • Validation: Use @Valid and @NotNull annotations to validate input automatically.
  • Global Exception Handling: Add @ControllerAdvice to handle errors consistently.
  • HTTP Status Codes: Always return appropriate codes (e.g., 201 Created for successful POST).
  • Performance: If your API handles large traffic, use connection pooling and caching layers, and ensure that JSON serialization is optimized.

Example of a DTO with validation:

package com.example.demo.model;

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Positive;

public class UserDto {

    @NotEmpty
    private String name;

    @Positive
    private int age;
    
    // getters and setters omitted for brevity
}

Using strong typing, structure, and Spring Boot’s conventions, your backend will be both robust and scalable.

Conclusion

Building REST APIs with Java doesn’t need to be intimidating. With Spring Boot, you can set up an API in minutes using minimal configuration. From here, you can integrate a database, add authentication, or deploy your service to the cloud. Mastering the fundamentals now paves the way for building production-grade APIs tomorrow.

 

Useful links: