← Back to Advanced Java Course | Chapter 10: Spring Boot | Lesson 2 of 6

Java Spring Boot REST API

A Spring Boot REST API lets you build web addresses that send and receive data, like a shop counter where customers ask for things. Controllers decide what to do for each request.
Syntax
java
@RestController
@RequestMapping("/path")
class ControllerName {
    @GetMapping("/{id}")
    public Type get(@PathVariable Long id) {
        // body
    }
}

REST Controllers

The @RestController annotation marks a class as handling HTTP requests directly, and combines @Controller with @ResponseBody so every method's return value is automatically serialized to JSON in the response, without you writing serialization code by hand.

Example: REST Controllers

java
import org.springframework.web.bind.annotation.RestController;
@RestController // combines @Controller + @ResponseBody
public class Main {
	public static void main(String[] args) {
		System.out.println("Every method's return value is serialized to JSON automatically");
	}
}

GET Request Handlers

Use @GetMapping to route incoming GET requests to a specific controller method, and @PathVariable to capture dynamic segments straight out of the URL path (like the id in /users/{id}) as a typed method parameter.

Example: GET Request Handlers

java
// Import org.springframework.web.bind.annotation.* so it can be used by its short name
import org.springframework.web.bind.annotation.*;
@RestController
// Define the class Main
public class Main {
	@GetMapping("/users/{id}")
	String getUser(@PathVariable int id) {
		// Send "User #" + id back to the caller
		return "User #" + id;
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(new Main().getUser(7));
	}
}

POST Request Handlers

Use @PostMapping to route incoming POST requests, and the @RequestBody annotation to have Spring automatically deserialize the incoming JSON request body directly into a Java object, saving you from manually parsing the payload.

Example: POST Request Handlers

java
// Import org.springframework.web.bind.annotation.* so it can be used by its short name
import org.springframework.web.bind.annotation.*;
@RestController
// Define the class Main
public class Main {
	// Define the record UserRequest (an immutable data carrier)
	record UserRequest(String name) {}
	@PostMapping("/users")
	String createUser(@RequestBody UserRequest request) {
		// Send "Created: " + request.name() back to the caller
		return "Created: " + request.name();
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(new Main().createUser(new UserRequest("Riya")));
	}
}

Custom Request Mappings

Prefixing a controller class with @RequestMapping lets you group all of its endpoints under a shared base URL path, which keeps a growing REST API organized into clear resource-based sections instead of every endpoint repeating a common prefix.

Example: Custom Request Mappings

java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users") // shared base path for every endpoint below
public class Main {
	@GetMapping("/{id}")
	String getUser(@PathVariable int id) { return "User #" + id; }
	public static void main(String[] args) {
		System.out.println(new Main().getUser(3));
	}
}

Content Negotiation

REST controllers can automatically format the same response as XML or JSON depending on the client's Accept header and the request's Content-Type, letting one endpoint serve multiple consumers without duplicating handler logic for each format.

Example: Content Negotiation

java
// Import org.springframework.web.bind.annotation.* so it can be used by its short name
import org.springframework.web.bind.annotation.*;
@RestController
// Define the class Main
public class Main {
	@GetMapping(value = "/data", produces = {"application/json", "application/xml"})
	String getData() {
		return "same handler serves JSON or XML based on Accept header";
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(new Main().getData());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using @Controller instead of @RestController and getting the return value treated as a view name, not as the response body.
  2. Forgetting @RequestBody on a POST method parameter, so the JSON body is not bound and the object is empty or null.
  3. Naming the path /users/{id} but the parameter userId without @PathVariable("id"), so Spring cannot match the two.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.