⚒️ Types of API Versioning
- URI Versioning
- Request Parameter
- (Custom) Header Versioning
URI Approach
Example:
http://host/v1/student
http://host/v2/student
@RestController
public class StudentVersioningController {
@GetMapping("v1/student")
public StudentV1 studentV1() {
return new StudentV1("Bob Charlie");
}
@GetMapping("v2/student")
public StudentV2 studentV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}
}
Request Parameter Approach
Example:
http://host/student/param?version=1
http://host/student/param?version=2
@RestController
public class StudentVersioningController {
@GetMapping(value = "/student/param", params = "version=1")
public StudentV1 paramV1() {
return new StudentV1("Bob Charlie");
}
@GetMapping(value = "/student/param", params = "version=2")
public StudentV2 paramV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}
}
(Custom) Header Approach
Example:
http://host/student
**headers=[X-API-VERSION=1]**
http://host/student
**headers=[X-API-VERSION=2]**
@RestController
public class StudentVersioningController {
@GetMapping(value = "/student", headers = "X-API-VERSION=1")
public StudentV1 headerV1() {
return new StudentV1("Bob Charlie");
}
@GetMapping(value = "/student", headers = "X-API-VERSION=2")
public StudentV2 headerV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}
}
🤔 Following factors affect the choice of versioning:
- URI Pollution — URL versions and Request Param versioning pollute the URI space.
- Misuse of HTTP Headers — Accept Header is not designed to be used for versioning.
- Caching — If you use Header based versioning, we cannot cache just based on the URL. You would need take the specific header into consideration.
- Can we execute the request on the browser? — If you have non technical consumers, then the URL based version would be easier to use as they can be executed directly on the browser.
- API Documentation — How do you get your documentation generation to understand that two different urls are versions of the same service?
🛑 BUT, there is no perfect solution for versioning
Famous Companies and their way of API Versioning:
- (Custom) Headers: Microsoft
- URI Versioning: Twitter
- Request Parameter Versioning: Amazon
Keep Coding 🚀,
Chris