REST API versioning in Go
Published: Oct 6, 2024
Table of content
• • •
Versioning the API
To make it easy for the client, we will "pack" the endpoints into versioned APIs. This way, the client developer can simply update the API calls and then increase the version of the endpoints (e.g., from "/api/v1/" to "/api/v2/").
We can simply assign the endpoints to the correct handler. And if an endpoint hasn't changed between versions, we can simply keep it.
func apiV1(r *gin.Engine) {
v1 := r.Group("/api/v1")
v1.GET("/books", handlers.HandlerGetBooks1)
v1.GET("/authors", handlers.GetAuthors1)
}
// In V2, the books api has changed
func apiV2(r *gin.Engine) {
v1 := r.Group("/api/v2")
v1.GET("/books", handlers.HandlerGetBooks2)
v1.GET("/authors", handlers.GetAuthors1)
}
func main() {
r := gin.Default()
apiV1(r)
apiV2(r)
}
Now old clients can still run using the "/api/v1/books" call, while newer clients can use the new "/api/v2/books" call.