REST API versioning in Go

Published: Oct 6, 2024

Table of content

• • •

Versioning individual endpoints

I want to version the whole endpoint. When fixing issues or maintaining the codebase, creating a version is not necessary, as long as the input and the output remain the same. But as soon as the input or the output changes, e.g., because you want to define this input differently or the models change, you should version the endpoint to prevent breaking changes in clients.

To version the endpoints, I simply put a number behind the name of the handler function. This makes it easy to see what versions exist and to be able to still fix bugs in older but still supported versions.

func HandlerGetBooks1(c *gin.Context) {
  // Code
}

func HandlerGetBooks2(c *gin.Context) {
  // Code
}

The handlers would essentially perform the same function, but with different inputs and outputs. In this example, it could be that the "Book" model has changed. Meanwhile, the first version still handles requests using the old model and eventually becomes deprecated, while the second version uses the new model.