AI Hints
Home›Spring Boot Tutorial›Testing with curl, @RestController and @GetMapping
Spring Boot · Lesson 15 of 120

@GetMapping

Mapping paths.

⏱ 2 min read▶ Video at 19:12🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

At Get Mapping connects a path to a method. It has a few handy tricks, that keep our URLs tidy.

  • Path → method
  • A few tricks
  • Tidy URLs

Mapping rules

At Request Mapping on the class adds a prefix, to every path inside it. A mapping can list several paths, in curly braces. An empty path means the prefix itself. And paths can have many parts, separated by slashes.

keyvalue
@RequestMapping("/api")prefix for the class
{"", "/home"}several paths
""the prefix itself
"/books/count"many parts

A prefix and several paths

At Request Mapping slash api goes on the class. Home answers two paths, the empty path, and slash home. Count answers slash books slash count. Run it. Slash api, and slash api slash home, both reach home. Slash api slash books slash count gives three. And slash home on its own is not found, because the prefix is missing.

ShopController.javajava
@RestController
@RequestMapping("/api")
public class ShopController {

    @GetMapping({"", "/home"})
    public String home() {
        return "Welcome to the shop";
    }

    @GetMapping("/books/count")
    public int count() {
        return 3;
    }
}
Output
$ curl localhost:8080/api
Welcome to the shop
$ curl localhost:8080/api/home
Welcome to the shop
$ curl localhost:8080/api/books/count
3
$ curl -i localhost:8080/home | head -1
HTTP/1.1 404
Also uses _curl.sh
curl localhost:8080/api
curl localhost:8080/api/home
curl localhost:8080/api/books/count
curl -i localhost:8080/home | head -1

Quick check

Here's a quick check. The class has at Request Mapping slash shop, and a method has at Get Mapping slash hours. Which URL reaches that method? Think about it. The answer is slash shop slash hours, because the class prefix comes first.

Quick check
@RequestMapping("/shop") on the class, @GetMapping("/hours") on the method. Which URL works?

Summary

At Get Mapping maps paths to methods. At Request Mapping on the class adds a prefix, to every path. Next, path variables.

Key takeaways
  • @GetMapping("/path")
  • Several paths
  • @RequestMapping prefix
Next up: Path Variables — values inside the URL