name: Automated API Documentation

sort: 2

Otomatik API Dökümantasyonu

Otomatik dökümantasyon çok arzu edilen, çok havalı bir özellik. Bu özellik Beego’ya da eklendi. Beego sadece API development hızınızı arttırmayacak, ayrıca kolay bir API kullanımı sunacak.

Beego’ya API dökümantasyonu için swagger entegre edilmiştir. Swagger çok kolay, çok güçlü API dökümantasyonu oluşturur.

Tamam, hadi şimdi deneyelim. Öncelikle aşağıdaki komutla yeni bir API uygulaması oluşturalım :

bee api beeapi

API global ayarları

Aşağıdaki yorum satırlarını routers/router.go dosyasının üstüne ekleyelim :

  1. // @APIVersion 1.0.0
  2. // @Title mobile API
  3. // @Description mobile has every tool to get any job done, so codename for the new mobile APIs.
  4. // @Contact astaxie@gmail.com
  5. package routers

Yukarıdaki kod bloğunda gördüğünüz global tanımlamalar ve daha fazlası aşağıdaki gibidir :

  • @APIVersion
  • @Title
  • @Description
  • @Contact
  • @TermsOfServiceUrl
  • @License
  • @LicenseUrl
  • @Name
  • @URL
  • @LicenseUrl
  • @License
  • @Schemes
  • @Host

Router Eşleştirme

Şimdilik otomatik API dökümantasyonu NSNamespace ve NSInclude seviye tanımlamalarını destekliyor. İlk seviye API versiyonunu, ikinci seviye ise modülleri temsil eder.

  1. func init() {
  2. ns :=
  3. beego.NewNamespace("/v1",
  4. beego.NSNamespace("/customer",
  5. beego.NSInclude(
  6. &controllers.CustomerController{},
  7. &controllers.CustomerCookieCheckerController{},
  8. ),
  9. ),
  10. beego.NSNamespace("/catalog",
  11. beego.NSInclude(
  12. &controllers.CatalogController{},
  13. ),
  14. ),
  15. beego.NSNamespace("/newsletter",
  16. beego.NSInclude(
  17. &controllers.NewsLetterController{},
  18. ),
  19. ),
  20. beego.NSNamespace("/cms",
  21. beego.NSInclude(
  22. &controllers.CMSController{},
  23. ),
  24. ),
  25. beego.NSNamespace("/suggest",
  26. beego.NSInclude(
  27. &controllers.SearchController{},
  28. ),
  29. ),
  30. )
  31. beego.AddNamespace(ns)
  32. }

Uygulama Yorumları

Bu kısım yorum eklemenin en önemli kısmıdır. Örnek verirsek :

  1. package controllers
  2. import "github.com/astaxie/beego"
  3. // CMS API
  4. type CMSController struct {
  5. beego.Controller
  6. }
  7. func (c *CMSController) URLMapping() {
  8. c.Mapping("StaticBlock", c.StaticBlock)
  9. c.Mapping("Product", c.Product)
  10. }
  11. // @Title getStaticBlock
  12. // @Summary getStaticBlock
  13. // @Deprecated Deprecated
  14. // @Description get all the staticblock by key
  15. // @Param key path string true "The static block key." default_value
  16. // @Success 200 {object} ZDT.ZDTMisc.CmsResponse
  17. // @Failure 400 Bad request
  18. // @Failure 404 Not found
  19. // @Accept json
  20. // @router /staticblock/:key [get]
  21. func (c *CMSController) StaticBlock() {
  22. }
  23. // @Title Get Product list
  24. // @Description Get Product list by some info
  25. // @Success 200 {object} models.ZDTProduct.ProductList
  26. // @Param category_id query int false "category id"
  27. // @Param brand_id query int false "brand id"
  28. // @Param query query string false "query of search"
  29. // @Param segment query string false "segment"
  30. // @Param sort query string false "sort option"
  31. // @Param dir query string false "direction asc or desc"
  32. // @Param offset query int false "offset"
  33. // @Param limit query int false "count limit"
  34. // @Param price query float false "price"
  35. // @Param special_price query bool false "whether this is special price"
  36. // @Param size query string false "size filter"
  37. // @Param color query string false "color filter"
  38. // @Param format query bool false "choose return format"
  39. // @Failure 400 no enough input
  40. // @Failure 500 get products common error
  41. // @router /products [get]
  42. func (c *CMSController) Product() {
  43. }

Yukarıdaki kod içerisinde CMSController‘ın üzerine modülün açıklamasını içeren bir yorum ekledik. Sonrasında her controller metoduna yorumları tanımladık.

Aşağıdaki liste Swagger’ın desteklediği yorum tanımlamalarıdır :

  • @Accept Kabul edilen tipleri ifade eder (json/xml/html/plain)
  • @Deprecated Artık kullanılmamasını gereken yerleri ifade eder
  • @Title

    API’ın başlığıdır. String tipindedir ve tanımlama ilk boşluktan sonra başlar.

  • @Description

    API için açıklama kısmıdır. String tipindedir ve tanımlama ilk boşluktan sonra başlar.

  • @Param

    @Param defines the parameters sent to the server. There are five columns for each @Param:

    1. parameter key;
    2. parameter sending type; It can be formData, query, path, body or header. formData means the parameter sends by POST ( set Content-Type to application/x-www-form-urlencoded ) . query means the parameter sends by GET in url. path means the parameter in the url path, such as key in the former example. body means the raw data send from request body. header means the parameter is in request header.
    3. parameter data type
    4. required
    5. comment
    6. default value
  • @Success

    The success message returned to client. Three parameters.

    1. status code.
    2. return type; Must wrap with {}.
    3. returned object or string. For {object}, use path and the object name of your project here and bee tool will look up the object while generating the docs. For example models.ZDTProduct.ProductList represents ProductList object under /models/ZDTProduct

      Use space to separate these three parameters

  • @Failure

    The failure message returned to client. Two parameters separated by space.

    1. Status code.
    2. Error message.
  • @router

    Router information. Two parameters separated by space.

    1. The request’s router address.
    2. Supported request methods. Wrap in []. Use , to separate multiple methods.

Generate document automatically

Make it work by following the steps:

  1. Enable docs by setting EnableDocs = true in conf/app.conf.
  2. Use bee run -downdoc=true -gendoc=true to run your API application and rebuild document automatically.
  3. Visit `swagger document from API project’s URL and port. (see item #1 below)

Your API document is available now. Open your browser and check it.

Otomatik API Dökümantasyonu - 图1

Otomatik API Dökümantasyonu - 图2

Problems You May Have

  1. CORS Two solutions:

    1. Integrate swagger into the application. Download swagger and put it into project folder. (bee run -downdoc=true will also download it and put it into project folder) And before beego.Run() in func main() of main.go

      1. if beego.BConfig.RunMode == "dev" {
      2. beego.BConfig.WebConfig.DirectoryIndex = true
      3. beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
      4. }

      And then visit swagger document from API project’s URL and port.

    2. Make API support CORS

      1. ctx.Output.Header("Access-Control-Allow-Origin", "*")
  2. Other problems. This is a feature used in my own project. If you have some other problems please fire issues to us.