Gin REST API Example
Simple REST API project which exposes Endpoints to perfom CRUD operation on Book Resource.
- Gin
- MongoDB
- Gin-Swagger
You can find the instructions to install MongoDB on different OS here -
MongoDB installation instructions
If you need UI to browse MongoDB, then you can try -
Complete documentation on how to use Gin-Swagger and its dependencies is her Gin-Swagger GitHub
- When you execute
$ swag init
You might get the error :
command not found: swag
This happens because the swag executeable get installed at location $GOPATH/bin/swag (generally $GOPATH is /Users/{user}/go) and which is not on system PATH.
You can resolve this issue by modifying PATH environment variable in ~/.profile, or in ~/.bash_profile to export swag path.
e.g. on Mac you can modify ~/.bash_profile and put below commands
export SWAG_HOME=/Users/{user}/go
export PATH="${SWAG_HOME}/bin:$PATH"
- Error : not yet registered swag and Failed to load API definition message on Swagger UI
You can resolve this issue by importing docs generated by Swag CLI command swag init. e.g. for this project the import for docs in main.go looks like
_ "gin-rest-api/docs"
- 404 page not found :
When you visit Swagger UI on localhost at http://localhost:8080/swagger/index.html you get 404 page not found.
You can resolve this issue by registering Swagger handler on the route e.g. below is snippet from main.go from this project
// @title Library API
// @version 1.0
// @license.name Apache 2.0
// @description Library API Server.
// @host localhost:8080
// @contact.name Deepak Muthekar
// @BasePath /api/v1
func main() {
router := gin.Default()
router.Use(CustomMiddleware())
router.Use(cors.Default())
api := router.Group("api/v1")
{
book := new(controller.BookController)
api.GET("/books", book.List)
api.GET("/books/:id", book.Get)
api.POST("/books", book.Create)
api.PUT("/books", book.Update)
api.DELETE("/books/:id", book.Delete)
}
//Register handler for Swagger
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
router.Run()
}