@PathVariable

@PathVariable() binds a controller parameter to a {variable} of the mapping's path, such as isbn in /books/{isbn}.

Why

When the path names the resource (/books/978-0, /authors/42/books), the value belongs in the path rather than in the query. The annotation takes it from the matched path, decodes it and converts it to the parameter's type, so the method receives an int or an enum instead of a text to parse.

Example

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

enum Format { pdf, epub }

@RestController()
class BookController {
  // GET /books/978-0: isbn is '978-0'.
  @GetMapping('/books/{isbn}')
  String find(@PathVariable() String isbn) => 'book $isbn';

  // The parameter has another name than the variable, so name it.
  // GET /authors/42/books: authorId is 42; /authors/x/books is a 400.
  @GetMapping('/authors/{id}/books')
  String byAuthor(@PathVariable('id') int authorId) => 'author $authorId';

  // A regular expression lets only digits in: /orders/abc is a 404.
  @GetMapping(r'/orders/{id:\d+}')
  String order(@PathVariable() int id) => 'order $id';

  // An enum, by name in any case: /downloads/978-0/EPUB.
  @GetMapping('/downloads/{isbn}/{format}')
  String download(@PathVariable() String isbn, @PathVariable() Format format) =>
      '$isbn as ${format.name}';

  // The rest of the path, with its leading slash:
  // GET /files/docs/a/b.txt: path is '/docs/a/b.txt'.
  @GetMapping('/files/{*path}')
  String file(@PathVariable() String path) => path;

  // A list from one segment: GET /books/batch/1,2,3: ids is [1, 2, 3].
  @GetMapping('/books/batch/{ids}')
  List<int> batch(@PathVariable() List<int> ids) => ids;
}

Parameters

Name Type Default Meaning
name (positional) String? null The name of the path variable. null: the variable named like the Dart parameter.

Rules

In Spring (Java)

@GetMapping("/authors/{id}/books")
List<Book> byAuthor(@PathVariable("id") int authorId) { ... }

Differences that matter:

See also