github.com/go-swagger/go-swagger@v0.31.0/docs/faq/faq_spec.md (about)

     1  ---
     2  title: About generating a spec document
     3  date: 2023-01-01T01:01:01-08:00
     4  draft: true
     5  ---
     6  <!-- Questions about spec generation -->
     7  ## Spec generation from source
     8  
     9  ### Is there an example to generate a swagger spec document from the code?
    10  _Use-Case_: I have read the swagger.json generation and feel confused. Could you please give an example for it?
    11  
    12  **Answer**: this folder uses most of the annotations
    13  
    14  https://github.com/go-swagger/go-swagger/tree/master/fixtures/goparsing/petstore
    15  
    16  >This begs for 3 questions :
    17  > - Q1: Does a struct for Parameter model have to be declared in the SAME .go file where the swagger:route is declared for a router function?
    18  > - Q2: Assume that I have a route "/services/{serviceName}", how would I named the field associated with the path "{serviceName}" above in a struct wrapper for path params?
    19  > - Q3: Is the annotations case sensitive like "Required" vs "required"?. I see mixed examples about this.
    20  
    21  **Answers**:
    22  
    23  - Q1: nope. It needs to be declared in the same app and it needs to be imported so that goswagger can find it by following imports starting at the main package.
    24  - Q2: you would add all of them in the parameter struct at this moment, in the case of parameters you would add a doc comment: // in: path. Take a look at some of the generated code examples because they contain all the known annotations as well.
    25  - Q3: not case sensitive, didn't want to have debates over casing. Whatever looks good to you in docs is what you can use.
    26  
    27  *One more question: Can methods in an interface be annotated?*
    28  
    29  **Answer**: only when it's used in a discriminator IIRC. There is code in the scan package that treats nullary methods as properties if certain conditions are met.
    30  
    31  >My generated spec is now working but seems to be missing a parameter "description" to indicate to end user of the API URL endpoint of what's its doing. Example below, I wanted the line "disable/enable a compute node EC2 machine with a given IP address" to show up as some sort of description for the parameter... Am I missing something?
    32  
    33  ```golang
    34  // v2PutXXX disable/enable a compute node EC2 machine with a given IP address
    35  //
    36  // swagger:route PUT /compute/nodes/{nodeIPAddress} v2PutXXX
    37  //
    38  // Disable/enable a compute node machine with a given IP address
    39  //
    40  // Produces:
    41  // - application/json
    42  //
    43  // Consumes:
    44  // - application/json
    45  //
    46  // Schemes: http
    47  //
    48  // Responses:
    49  // default: errorResp
    50  // 200: okResp
    51  //
    52  func v2PutXXX(....)
    53  ```
    54  
    55  **Answer**: you still need to add enlist a struct as parameters for the operation.
    56  https://goswagger.io/generate/spec/params.html
    57  
    58  *Is there an example how to generate example values from the code?*
    59  
    60  **Answer**: I don't think that is supported at the moment
    61  
    62  Originally from issue [#213](https://github.com/go-swagger/go-swagger/issues/213).
    63  
    64  ### Extra function in example?
    65  In file: `go-swagger/fixtures/goparsing/classification/operations/todo_operation.go`,
    66  `Func: mountItem` looks like extra function. Could you explain?
    67  
    68  **Answer**: swagger tool generates a correct specification for proposed routes without calling fake func mountItem.
    69  
    70  The main rule is **empty line between `swagger:routes`** like that:
    71  
    72  ```golang
    73  // ServeAPI serves the API for this record store
    74  func ServeAPI(host, basePath string, schemes []string) error {
    75      // swagger:route GET /pets pets users listPets
    76  
    77      // swagger:route GET /orders orders listOrders
    78  
    79      // swagger:route POST /orders orders createOrder
    80  
    81      // swagger:route GET /orders/{id} orders orderDetails
    82  
    83      // swagger:route PUT /orders/{id} orders updateOrder
    84  
    85      // swagger:route DELETE /orders/{id} orders deleteOrder
    86  return nil
    87  }
    88  ```
    89  
    90  Originally from issue [#68](https://github.com/go-swagger/go-swagger/issues/68).
    91  
    92  ### Maps as swagger parameters
    93  _Use-case_: I'm using go-swagger to generate my Swagger docs from code, and I came across a problem with a given parameter.
    94  
    95  When I annotate a given struct that has a `map[KeyType]OtherKeyType` with `swagger:parameters`,
    96  it returns `items doesn't support maps`.
    97  
    98  **Answer**: **this is not supported**
    99  
   100  - In non-body parameters maps are not supported in the swagger spec
   101  - In body parameters, a JSON schema only allows maps with string keys
   102  
   103  Originally from issue [#960](https://github.com/go-swagger/go-swagger/issues/960).
   104  
   105  ### How to define a swagger response that produces a binary file?
   106  
   107  _Use-case_: annotating a go struct in order to produce a response as application/octet-stream.
   108  
   109  Example:
   110  I would like to get a generated specification like:
   111  ```JSON
   112  "fileResponse": {
   113    "description": "OK",
   114    "schema": {
   115      "type": "file"
   116    }
   117  }
   118  ```
   119  >However, I am unable to figure out how to do this with go-swagger response struct and annotations.
   120  
   121  **Answer**: you can use `runtime.File` or `os.File` in your struct:
   122  ```golang
   123  type fileResponse struct {
   124      // In: body
   125      File runtime.File
   126  }
   127  ```
   128  Originally from issue [#1003](https://github.com/go-swagger/go-swagger/issues/1003).
   129  
   130  ### How to use swagger params?
   131  _Use-Case_: I defined a route with!
   132  ```golang
   133  // swagger:route GET /services/{serviceName}/version/{version} pets listOneService
   134  ```
   135  
   136  *How to comment the two params('serviceName' and 'version')?*
   137  
   138  **Answer**: `swagger:params` is used to indicate which operations the properties of the operation are included in the struct.
   139  
   140  So you'd use something like these:
   141  https://github.com/go-swagger/go-swagger/blob/master/fixtures/goparsing/petstore/rest/handlers/orders.go#L24-L46
   142  
   143  or:
   144  
   145  ```golang
   146  // swagger:params listOneService
   147  type ListOneParams struct {
   148      // ServiceName description goes here
   149      //
   150      // in: path
   151      // required: true
   152      ServiceName string `json:"serviceName"`
   153  
   154      // Version description goes here
   155      //
   156      // in: path
   157      // required: true
   158      Version string `json:"version"`
   159  }
   160  ```
   161  
   162  Originally from issue [#668](https://github.com/go-swagger/go-swagger/issues/668).
   163  
   164  ### Empty definitions
   165  _Use-Case_: I don't understand how to deal with model annotation.
   166  When I generate a spec from source, I get empty definitions.
   167  
   168  **Answer**: models are discovered through usage in parameter and/or response objects.
   169  
   170  If the model isn't used through a parameter or response object it's not part of the API because there is no way that it goes in or out through the API.
   171  
   172  Example:
   173  
   174  doc.go
   175  ```golang
   176  // Schemes: http, https
   177  // Host: localhost
   178  // BasePath: /v1
   179  // Version: 0.0.1
   180  // License: MIT http://opensource.org/licenses/MIT
   181  //
   182  // Consumes:
   183  // - application/json
   184  // - application/xml
   185  //
   186  // Produces:
   187  // - application/json
   188  // - application/xml
   189  //
   190  //
   191  // swagger:meta
   192  package main
   193  ...
   194  ```
   195  user.go
   196  ```golang
   197  // Copyright 2015 go-swagger maintainers
   198  //
   199  // ...
   200  
   201  package models
   202  
   203  // User represents the user for this application
   204  //
   205  // A user is the security principal for this application.
   206  // It's also used as one of main axis for reporting.
   207  //
   208  // A user can have friends with whom they can share what they like.
   209  //
   210  // swagger:model
   211  type User struct {
   212      // the id for this user
   213      //
   214      // required: true
   215      // min: 1
   216      ID int64 `json:"id"`
   217  
   218      // the name for this user
   219      // required: true
   220      // min length: 3
   221      Name string `json:"name"`
   222  }
   223  ```
   224  
   225  Originally from issue [#561](https://github.com/go-swagger/go-swagger/issues/561).
   226  
   227  ### Documentation or tutorials on code annotation
   228  _Use-Case_: documentation is scant on how to generate swagger files from annotations.
   229  Is it really all there in http://goswagger.io/generate/spec/?
   230  
   231  **Answer**: yes, it's all in there (or directly in the repo: https://github.com/go-swagger/go-swagger/tree/master/docs/generate/spec)
   232  
   233  *How about some code examples that show annotations being used?*
   234  
   235  **Answer**: there is an "examples" folder in the repo.
   236  All generated code also uses all the annotations that are applicable for it.
   237  
   238  https://github.com/go-swagger/go-swagger/tree/master/examples/todo-list
   239  
   240  And also: https://github.com/go-swagger/go-swagger/tree/master/fixtures/goparsing/classification
   241  (this is the code used to test parsing the annotations).
   242  
   243  Please bear in mind that this is a project (not a product) to which a number of volunteers have
   244  contributed significant amounts of free time to get it to where it is today.
   245  
   246  Improvement of documentation is always a good request.
   247  All help we can get is absolutely welcome.
   248  
   249  Originally from issue [#599](https://github.com/go-swagger/go-swagger/issues/599).
   250  
   251  ### Wrong schema in response structure?
   252  I set up this response struct:
   253  
   254  ```golang
   255  // swagger:response SuccessResponse
   256  type SuccessResponse struct {
   257      // In: body
   258      Data ResponseData `json:"data"`
   259  }
   260  
   261  type ResponseData struct {
   262      Field1 string `json:"field1"`
   263      Field2 string `json:"field2"`
   264  }
   265  ```
   266  Expected schema:
   267  ```JSON
   268  {
   269    "responses": {
   270      "ErrorResponse": {},
   271      "SuccessResponse": {
   272        "description": "SuccessResponse is success response",
   273        "schema": {
   274          "$ref": "#/definitions/SuccessResponse"
   275        }
   276      }
   277    }
   278  }
   279  ```
   280  but getting instead:
   281  ```JSON
   282  {
   283    "responses": {
   284      "ErrorResponse": {},
   285      "SuccessResponse": {
   286        "description": "SuccessResponse is success response",
   287        "schema": {
   288          "$ref": "#/definitions/ResponseData"
   289        }
   290      }
   291    }
   292  }
   293  ```
   294  I know this is expected working behavior, but
   295  I don't want to add additional level of structs just to support pretty output.
   296  
   297  **Answer**: you can rename the model in the json with the swagger:model doc tag on the response
   298  data struct, that would get you the expected output.
   299  
   300  ```golang
   301  // swagger:response SuccessResponse
   302  type SuccessResponse struct {
   303      // In: body
   304      Data ResponseData `json:"data"`
   305  }
   306  
   307  // swagger:model SuccessResponse
   308  type ResponseData struct {
   309      Field1 string `json:"field1"`
   310      Field2 string `json:"field2"`
   311  }
   312  ```
   313  
   314  Originally from issue [#407](https://github.com/go-swagger/go-swagger/issues/407).
   315  
   316  ### go-swagger not generating model info and showing error on swagger UI
   317  
   318  _Use-Case_: when I'm executing : `swagger generate spec -o ./swagger.json` to generate the json spec I'm getting:
   319  
   320  ```JSON
   321  {
   322    "consumes": ["application/json", "application/xml"],
   323    "produces": ["application/json", "application/xml"],
   324    "schemes": ["http", "https"],
   325    "swagger": "2.0",
   326    "info": {
   327      "description": "the purpose of this application is to provide an application\nthat is using plain go code to define an API\n\nThis should demonstrate all the possible comment annotations\nthat are available to turn go code into a fully compliant swagger 2.0 spec",
   328      "title": "User API.",
   329      "termsOfService": "there are no TOS at this moment, use at your own risk we take no responsibility",
   330      "contact": {
   331        "name": "John Doe",
   332        "url": "http://john.doe.com",
   333        "email": "john.doe@example.com"
   334      },
   335      "license": {
   336        "name": "MIT",
   337        "url": "http://opensource.org/licenses/MIT"
   338      },
   339      "version": "0.0.1"
   340    },
   341    "host": "localhost",
   342    "basePath": "/v2",
   343    "paths": {
   344      "/user": {
   345        "get": {
   346          "description": "This will show all available pets by default.\nYou can get the pets that are out of stock",
   347          "consumes": ["application/json", "application/x-protobuf"],
   348          "produces": ["application/json", "application/x-protobuf"],
   349          "schemes": ["http", "https", "ws", "wss"],
   350          "tags": ["listPets", "pets"],
   351          "summary": "Lists pets filtered by some parameters.",
   352          "operationId": "users",
   353          "security": [{
   354            "api_key": null
   355           },{
   356            "oauth": ["read", "write"]
   357            }
   358          ],
   359          "responses": {
   360            "200": {
   361              "$ref": "#/responses/someResponse"
   362            },
   363            "422": {
   364              "$ref": "#/responses/validationError"
   365            },
   366            "default": {
   367              "$ref": "#/responses/genericError"
   368            }
   369         }
   370      }
   371    }
   372  },
   373  "definitions": {}
   374  }
   375  ```
   376  
   377  Note that my definitions are empty, not sure why. If I paste the same json spec in http://editor.swagger.io/#/ It says
   378  ```
   379  Error
   380  Object
   381  message: "options.definition is required"
   382  code: "UNCAUGHT_SWAY_WORKER_ERROR"
   383  ```
   384  Any directions on what is the right way to generate swagger documentation would help
   385  
   386  **Answer**: can you move the `swagger:model` annotation to be the last line in the doc comments for a struct?
   387  
   388  Alternatively, I see some definitions for responses in your specification document, but no matching `swagger:response` definitions structs.
   389  ```golang
   390  // swagger:response errorResponse
   391  type ErrorResponse struct {
   392      // in: body
   393      Body struct {
   394          Message string `json:"error,omitempty"`
   395      }
   396  }
   397  
   398  // swagger:response validationError
   399  type ValidationError struct {
   400      // in: body
   401      Body struct {
   402          // required: true
   403          Message string `json:"error,omitempty"`
   404  
   405          Field string `json:"fieldName,omitempty"`
   406      }
   407  }
   408  
   409  // swagger:response someResponse
   410  type SomeResponse struct {
   411      // in: body
   412      Body *User `json:"body,omitempty"`
   413      }
   414  ```
   415  With the `--scan-models` generating option, you should have models picked up, regardless of whether they're in use somewhere else or not.
   416  
   417  <!-- Would need a recap/update on that
   418  ### Running on google app engine
   419  _Use-Case_: generating a spec for an app built for GoogleApp engine
   420  
   421  > App engine apps use some package imports which don't resolve when run with `go build: "appengine","appengine/datastore"`, etc. 
   422  > It seems like `swagger generate spec` fails if it can't first build my app.
   423  
   424  *To support app engine you'd need to remove that requirement.*
   425  
   426  > I would like to use go-swagger with my app engine project, so please make it parse the comments without first needing to build the app.
   427  
   428  > I tried adding the appengine build constraint, and it didn't error out, but it generated an empty spec.
   429  > at this point we make use of the go loader package. This allows us to discover your application and which files to scan for the doc comments.
   430  
   431  This application needs to read composed structs and so on, and it's a lot easier to interrogate the application if you know where all the files are and not just the ones you created in this particular folder.
   432  Unfortunately it does require to be able to read
   433  
   434  How about a main class that doesn't require appengine imports?
   435  I've personally never used appening so I don't really know what is involved.
   436  
   437  For an app engine app, typically the main.go doesn't require any of the special appengine imports... however it uses an init() function instead of a main() function, and in there is where you instantiate the router and bind all the routes to handlers. It is the handlers (usually in their own separate files) which need the appengine imports.
   438  
   439  I don't know if that's what you are asking about, but I know app engine fairly well so I can answer more questions if you have any.
   440  
   441  I guess what I mean is if your code doesn't compile, how are you running it?
   442  And what I also meant is; if this is important to you, you could look at forking and submitting a pull request.
   443  I, personally, still have a bunch of other things that need fixing in here before I want to look at a niche like appengine.
   444  
   445  Fair enough, if you're not interested in supporting app engine that's fine. I did try forking to fix that other bug that I filed, but the code was a bit over my head so I wasn't able to fix it.
   446  
   447  To answer your question, app engine apps don't get compiled with "go build", instead they are run on a dev server provided by the app engine SDK, and then they are deployed to app engine and run on the Google Cloud Platform infrastructure. The only reason they don't compile is because some of the packages ("appengine", "appengine/datastore", etc.) are only available in this SDK environment, they are not found in $GOPATH.
   448  
   449  Maybe app engine could improve this situation in the future, and then go-swagger wouldn't have to change to support it, but as it stands now this will not work with any app engine apps that use any of the appengine-specific imports.
   450  
   451  I will go back to using github.com/yvasiyarov/swagger for now, which doesn't require the app to build to generate the spec, but it is also not generating swagger 2.0, so I hope I can use your package sometime in the future.
   452  
   453  but the custom sdk they use also includes a custom go command doesn't it?
   454  I think the problem you're having is related to your GOPATH content and can be fixed there.
   455  
   456  afaik go always needs to compile your stuff, whether that's in the SDK env or not, have you tried installing go-swagger in the SDK provided GOPATH?
   457  
   458  I'll leave this open so i can track this
   459  Hmm that is an interesting thought. I will experiment more on this today.
   460  The app engine SDK definitely uses the regular system GOPATH to resolve most of the includes, but it maybe has another internal GOPATH also,
   461  I'm not sure. Will post my findings a bit later.
   462  
   463  Wow! You're right man! All that was needed to make generate spec work, was to add this to GOPATH:
   464  [go_appengine_sdk_location]/goroot
   465  
   466  The appengine includes are in there. It's working now, thanks for the insight!
   467  
   468  Originally from issue [#47](https://github.com/go-swagger/go-swagger/issues/47).
   469  -->
   470  <!-- Obsolete / Not helpfu
   471  ### Generating spec cannot import dependencies
   472  I'm unable to run the spec generator on my app. What am I doing wrong?
   473  https://gist.github.com/morenoh149/e44be6819bde86f52e7e
   474  
   475  I get many errors of the form ... .go:10:2: could not import github.com/facebookgo/stackerr (cannot find package "github.com/ ...
   476  
   477  execute $ swagger generate spec -o ./swagger.json in project folder
   478  
   479  which go version are you using?
   480  Are you using vendoring?
   481  
   482  go version go1.5.3 darwin/amd64
   483  
   484  I believe I have vendoring enabled yes. (Not sure I'm new).
   485  
   486  for this you require `export GO15VENDOREXPERIMENT=1`
   487  
   488  and also does your application compile? because go-swagger makes use of the same code the go compiler/imports/... etc use to discover all the involved packages. So I think it requires your code to be mostly compilable to be able to discover everything.
   489  
   490  However the errors seem to be related to it not being able to discover the dependencies
   491  
   492  I am running into this issue when trying to generate a swagger spec as well. I believe it is because I installed go with home brew on a mac so my library paths are different.
   493  
   494  Command I am running: swagger generate spec
   495  File I am trying to generate with: https://gist.github.com/gsquire/cce277b4bd10ba283f4522e896dc91d6
   496  
   497  Error trace:
   498  ```
   499  /Users/gsquire/scratch/test-swagger.go:14:2: could not import fmt (cannot find package "fmt" in any of:
   500  /usr/local/go/src/fmt (from $GOROOT)
   501  /Users/gsquire/gopath/src/fmt (from $GOPATH))
   502  /Users/gsquire/scratch/test-swagger.go:15:2: could not import net/http (cannot find package "net/http" in any of:
   503  /usr/local/go/src/net/http (from $GOROOT)
   504  /Users/gsquire/gopath/src/net/http (from $GOPATH))
   505  /Users/gsquire/scratch/test-swagger.go:18:14: undeclared name: http
   506  /Users/gsquire/scratch/test-swagger.go:18:38: undeclared name: http
   507  /Users/gsquire/scratch/test-swagger.go:19:2: undeclared name: fmt
   508  /Users/gsquire/scratch/test-swagger.go:23:2: undeclared name: http
   509  /Users/gsquire/scratch/test-swagger.go:24:2: undeclared name: http
   510  ```
   511  
   512  Are you on a Linux box? Like I said, I think it's a path issue since home brew installs it in a different location based on my output. I'll have to try on something that isn't mac.
   513  
   514  I uninstalled go-swagger from brew, installed it from source and it worked. So strange. And no, I installed it through brew:
   515  
   516  Originally from issue [#400](https://github.com/go-swagger/go-swagger/issues/400).
   517  -->
   518