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

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