As far as I know, we can version our APIs for some reason e.g. there is a change needed for the current API but we also need to use it in its previous state.
For this purpose, I generally use the following approach from start when building a project:
@RestController
@RequestMapping("/api/v1")
public class AuthController {
}
However, when I try to add another as mentioned on this page (in the same Controller file) I get Duplicate class error. However, I cannot add another class file to the same package.
So, could you pls clarify me about the following issues?
What is the purpose of using API versioning? Is the idea that I gave at the beginning one of the reason for that?
How can I use API versioning for my endpoints? Is there any extra implementation needed on another Spring Boot files?
CodePudding user response:
However, I cannot add another class file to the same package.
The obvious workaround here would be
@RestController
@RequestMapping("/api/") <----------
public class AuthController {
GetMapping("v1/users")
public List<String> getAllV1() {
...
}
GetMapping("v2/users")
public List<String> getAllV2() {
...
}
..relative you can have all methods exposed in the same class for both v1 and v2 implementations
}
What is the purpose of using API versioning
It is so that external people are able to know when your API has been modified as to know that they probably need to do changes in their consumer code. You may have shutdown v1
and offer only v2
now meaning they need to adapt to new implementation to continue functioning. Or you may offer both v1
and v2
so they don't nessesary need to adapt right now to continue to function but could start working to catch up with your new version in the future.
How can I use API versioning for my endpoints? Is there any extra implementation needed on another Spring Boot files?
Either you have a specific AuthController
and when you release a new version which impacts this controller you change the mapping from v1
into v2
, or you have 2 controllers one for v1
and one for v2
as linked to your question so you continue to expose both old implementation and new implementation under different urls. If this is not the case because of the constraint you mention However, I cannot add another class file to the same package.
then you can do the workaround I have written in this answer as to have both versions from the same file offered. But this would not be best practice to be used often.