REST APIsCore· 35 min read

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:

A RestController with two endpoints
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

  1. You visit a URL in the browser (a GET request).
  2. Spring finds the controller method whose @GetMapping matches that URL.
  3. The method runs and returns a value.
  4. 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?

Answer: A @RestController returns data directly. Whatever a method returns becomes the response body — plain text here, and JSON once you return objects.

✍️ Practice

  1. Add a /contact endpoint that returns your institute’s contact line.
  2. Add a /year endpoint that returns the text “2026”.

🏠 Homework

  1. Build a controller with four endpoints: /, /about, /services and /contact, each returning a sentence.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →