Once apps depend on your API, you can't just change it. Their code would break. Versioning lets old clients keep the old shape, while new clients get the new one.
The simplest way puts the version in the path, like slash api slash v one. Another sends it in a header, like API version, two. A query parameter works too. Pick one style, and use it everywhere.
Version one returns plain text. Version two returns JSON, with the author split into first, and last names. Both live side by side. Run it. Old clients call v one, and new clients call v two.
BookController.javajava
@RestControllerpublic class BookController { record Name(String first, String last) {} record BookV2(String title, Name author) {} @GetMapping("/api/v1/books/1") public String v1() { return "Dune by Frank Herbert"; } @GetMapping("/api/v2/books/1") public BookV2 v2() { return new BookV2("Dune", new Name("Frank", "Herbert")); }}
Output
$ curl localhost:8080/api/v1/books/1
Dune by Frank Herbert
$ curl localhost:8080/api/v2/books/1
{"title":"Dune","author":{"first":"Frank","last":"Herbert"}}
Spring seven has versioning built in. The mapping takes a version attribute. The properties say, read the version from the API version header, and default to one. Run it. Without a header, we get version one. With version two, we get JSON. And an unknown version is rejected, with four hundred.
BookController.javajava
@RestControllerpublic class BookController { record BookV2(String title, String author) {} @GetMapping(path = "/books/1", version = "1") public String v1() { return "Dune by Frank Herbert"; } @GetMapping(path = "/books/1", version = "2") public BookV2 v2() { return new BookV2("Dune", "Frank Herbert"); }}
Output
$ curl localhost:8080/books/1
Dune by Frank Herbert
$ curl -H "API-Version: 2" localhost:8080/books/1
{"title":"Dune","author":"Frank Herbert"}
$ curl -i -H "API-Version: 7" localhost:8080/books/1 | head -1
HTTP/1.1 400