AI Hints
Home›Spring Boot Tutorial›Path Variables, Query Parameters and Practice: A Greeting API
Spring Boot · Lesson 18 of 120

Practice: A Greeting API

Your turn.

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

Time to practise. We'll combine a path variable, and a query parameter, in one small API.

  • Your turn
  • Path + query
  • One small API

A greeting API

Your turn. Pause the video, and try this. Build GET slash greet slash name. It greets the name in a language. The lang parameter is optional, and defaults to English. Support French, and Spanish too. Here is one solution. A switch picks the word, from the language. Sam gets Hello, Ana gets Hola, and Leo gets Bonjour.

✍️ Exercise: A greeting API

GET /greet/{name}?lang=xx → "Hello, Sam!". lang is optional (default en); support fr → Bonjour and es → Hola.

Show hint

@PathVariable for name, @RequestParam(defaultValue = "en") for lang

Show solution
GreetingController.javajava
@RestController
public class GreetingController {

    @GetMapping("/greet/{name}")
    public String greet(@PathVariable String name,
                        @RequestParam(defaultValue = "en") String lang) {
        String word = switch (lang) {
            case "fr" -> "Bonjour";
            case "es" -> "Hola";
            default -> "Hello";
        };
        return word + ", " + name + "!";
    }
}
Output
$ curl localhost:8080/greet/Sam
Hello, Sam!
$ curl "localhost:8080/greet/Ana?lang=es"
Hola, Ana!
$ curl "localhost:8080/greet/Leo?lang=fr"
Bonjour, Leo!

What module two taught

HTTP methods say what to do, and status codes say how it went. JSON carries the data. At Rest Controller, and at Get Mapping, connect URLs to methods. And path variables, and query parameters, bring values in from the URL.

keyvalue
MethodsGET, POST, PUT, DELETE
Status200, 404, 400, 500
Mapping@RestController, @GetMapping
Inputs@PathVariable, @RequestParam

Summary

You can now build endpoints that read values from the URL. That's the end of module two. Next module, building a real REST API.

Key takeaways
  • Methods and status
  • @PathVariable
  • @RequestParam
Next up: What REST Is — a style for APIs