Your First RestController
A @RestController is a class whose methods answer web requests — this is how every Spring API begins.
What you will learn
- Create a @RestController class
- Map a method to a URL
- See the response in a browser
What a controller does
A controller is the part of your back-end that receives a request and sends back a response. In Spring Boot you write one with the @RestController annotation. The “Rest” part means it returns data (text or JSON), not a full web page.
Inside a controller you write methods, and you connect each method to a URL with a mapping annotation like @GetMapping.
Write one from scratch
Create a new file HelloController.java next to your main class:
package com.codingclave.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/")
public String home() {
return "Welcome to CodingClave API!";
}
@GetMapping("/about")
public String about() {
return "This API is built with Spring Boot.";
}
}Note: Output: Visiting http://localhost:8080/ -> Welcome to CodingClave API! Visiting http://localhost:8080/about -> This API is built with Spring Boot. Spring matched each URL to a method and sent its return value back as the response. No HTML, no extra setup.
How a request flows
- You visit a URL in the browser (a GET request).
- Spring finds the controller method whose
@GetMappingmatches that URL. - The method runs and returns a value.
- Spring sends that value back as the response.
Tip: No need to restart the server for every change if you add the Spring Boot DevTools dependency — it reloads your app automatically when you save. Handy while learning.
Watch out: Each URL path should map to one method. If two methods use the same @GetMapping("/about"), Spring will fail to start because it does not know which to call.
Q. What does a @RestController return by default?
✍️ Practice
- Add a
/contactendpoint that returns your institute’s contact line. - Add a
/yearendpoint that returns the text “2026”.
🏠 Homework
- Build a controller with four endpoints: /, /about, /services and /contact, each returning a sentence.