Repaso
EspaƱol

What does this endpoint do?

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public User get(@PathVariable Long id) {
        return userService.findById(id);
    }
}

Options

  1. Answers GET /api/users/42 with the user as JSON (Correct option)
  2. Answers POST /api/users and creates a new user
  3. Reads id from the JSON body of the request
  4. Deletes the user that has the id in the path

Answer

Responds to GET /api/users/42 with the user serialized as JSON, where id = 42

Why

@RestController means every method returns data written directly to the HTTP response body (Spring converts the object to JSON with Jackson).

@RequestMapping("/api/users") gives the base path, @GetMapping("/{id}") handles GET requests, and @PathVariable takes the value from the URL.

So GET /api/users/42 calls get(42).

Remember

@PathVariable = from the URL path. @RequestParam = from ?query. @RequestBody = from the body.

Key terms

Practice this question in Repaso