github.com/josephspurrier/go-swagger@v0.2.1-0.20221129144919-1f672a142a00/docs/generate/client.md (about) 1 # Generate an API client from a swagger spec 2 3 The toolkit has a command that will let you generate a client. 4 5 ### Client usage 6 7 ``` 8 Usage: 9 swagger [OPTIONS] generate client [client-OPTIONS] 10 11 generate all the files for a client library 12 13 Application Options: 14 -q, --quiet silence logs 15 --log-output=LOG-FILE redirect logs to file 16 17 Help Options: 18 -h, --help Show this help message 19 20 [client command options] 21 -c, --client-package= the package to save the client specific code (default: client) 22 -P, --principal= the model to use for the security principal 23 --default-scheme= the default scheme for this API (default: http) 24 --default-produces= the default mime type that API operations produce (default: application/json) 25 --default-consumes= the default mime type that API operations consume (default: application/json) 26 --skip-models no models will be generated when this flag is specified 27 --skip-operations no operations will be generated when this flag is specified 28 -A, --name= the name of the application, defaults to a mangled value of info.title 29 30 Options common to all code generation commands: 31 -f, --spec= the spec file to use (default swagger.{json,yml,yaml}) 32 -t, --target= the base directory for generating the files (default: ./) 33 --template=[stratoscale] load contributed templates 34 -T, --template-dir= alternative template override directory 35 -C, --config-file= configuration file to use for overriding template options 36 -r, --copyright-file= copyright file used to add copyright header 37 --additional-initialism= consecutive capitals that should be considered intialisms 38 --allow-template-override allows overriding protected templates 39 --skip-validation skips validation of spec prior to generation 40 --dump-data when present dumps the json for the template generator instead of generating files 41 --with-expand expands all $ref's in spec prior to generation (shorthand to --with-flatten=expand) 42 --with-flatten=[minimal|full|expand|verbose|noverbose|remove-unused] flattens all $ref's in spec prior to generation (default: minimal, verbose) 43 44 Options for model generation: 45 -m, --model-package= the package to save the models (default: models) 46 -M, --model= specify a model to include in generation, repeat for multiple (defaults to all) 47 --existing-models= use pre-generated models e.g. github.com/foobar/model 48 --strict-additional-properties disallow extra properties when additionalProperties is set to false 49 --keep-spec-order keep schema properties order identical to spec file 50 51 Options for operation generation: 52 -O, --operation= specify an operation to include, repeat for multiple (defaults to all) 53 --tags= the tags to include, if not specified defaults to all 54 -a, --api-package= the package to save the operations (default: operations) 55 --with-enum-ci set all enumerations case-insensitive by default 56 --skip-tag-packages skips the generation of tag-based operation packages, resulting in a flat generation 57 ``` 58 59 ### Build a client 60 61 There is an example client provided at: https://github.com/go-swagger/go-swagger/tree/master/examples/todo-list/client 62 63 To generate a client: 64 65 ``` 66 swagger generate client -f [http-url|filepath] -A [application-name] [--principal [principal-name]] 67 ``` 68 69 If you want to debug what the client is sending and receiving you can set the environment value DEBUG to a non-empty 70 value. 71 72 73 Use a default client, which has an HTTP transport: 74 75 ```go 76 import ( 77 "log" 78 79 "github.com/myproject/client/operations" 80 "github.com/go-openapi/strfmt" 81 "github.com/go-openapi/spec" 82 83 apiclient "github.com/myproject/client" 84 httptransport "github.com/go-openapi/runtime/client" 85 ) 86 87 func main() { 88 89 // make the request to get all items 90 resp, err := apiclient.Default.Operations.All(operations.AllParams{}) 91 if err != nil { 92 log.Fatal(err) 93 } 94 fmt.Printf("%#v\n", resp.Payload) 95 } 96 ``` 97 98 The client runtime allows for a number of [configuration 99 options](https://godoc.org/github.com/go-openapi/runtime/client#Runtime) to be set. 100 To then use the client, and override the host, with a HTTP transport: 101 102 ```go 103 import ( 104 "os" 105 "log" 106 107 "github.com/myproject/client/operations" 108 "github.com/go-openapi/strfmt" 109 "github.com/go-openapi/spec" 110 111 apiclient "github.com/myproject/client" 112 httptransport "github.com/go-openapi/runtime/client" 113 ) 114 115 func main() { 116 117 // create the transport 118 transport := httptransport.New(os.Getenv("TODOLIST_HOST"), "", nil) 119 120 // create the API client, with the transport 121 client := apiclient.New(transport, strfmt.Default) 122 123 // to override the host for the default client 124 // apiclient.Default.SetTransport(transport) 125 126 // make the request to get all items 127 resp, err := client.Operations.All(operations.AllParams{}) 128 if err != nil { 129 log.Fatal(err) 130 } 131 fmt.Printf("%#v\n", resp.Payload) 132 } 133 ``` 134 135 ### Authentication 136 137 The client supports 3 authentication schemes: 138 139 * [Basic Auth](https://godoc.org/github.com/go-openapi/runtime/client#BasicAuth) 140 * [API key auth in header or query](https://godoc.org/github.com/go-openapi/runtime/client#APIKeyAuth) 141 * [Bearer token header for oauth2](https://godoc.org/github.com/go-openapi/runtime/client#BearerToken) 142 143 ```go 144 import ( 145 "os" 146 "log" 147 148 "github.com/myproject/client/operations" 149 "github.com/go-openapi/strfmt" 150 "github.com/go-openapi/spec" 151 152 apiclient "github.com/myproject/client" 153 httptransport "github.com/go-openapi/runtime/client" 154 ) 155 156 func main() { 157 158 // create the API client 159 client := apiclient.New(httptransport.New("", "", nil), strfmt.Default) 160 161 // make the authenticated request to get all items 162 bearerTokenAuth := httptransport.BearerToken(os.Getenv("API_ACCESS_TOKEN")) 163 // basicAuth := httptransport.BasicAuth(os.Getenv("API_USER"), os.Getenv("API_PASSWORD")) 164 // apiKeyQueryAuth := httptransport.APIKeyAuth("apiKey", "query", os.Getenv("API_KEY")) 165 // apiKeyHeaderAuth := httptransport.APIKeyAuth("X-API-TOKEN", "header", os.Getenv("API_KEY")) 166 resp, err := client.Operations.All(operations.AllParams{}, bearerTokenAuth) 167 // resp, err := client.Operations.All(operations.AllParams{}, basicAuth) 168 // resp, err := client.Operations.All(operations.AllParams{}, apiKeyQueryAuth) 169 // resp, err := client.Operations.All(operations.AllParams{}, apiKeyHeaderAuth) 170 if err != nil { 171 log.Fatal(err) 172 } 173 fmt.Printf("%#v\n", resp.Payload) 174 } 175 ``` 176 177 ### Consuming an XML API 178 179 In order to enable XML support, you need to set the command options `--default-consumes` or `--default-produces` to an XML mime type like `application/xml` when generating the client: 180 181 ``` 182 swagger generate client -f [http-url|filepath] -A [application-name] --default-consumes application/xml 183 ``` 184 185 This is necessary regardless of whether your swagger specification already specifies XML in the consumes and produces properties. 186 187 An example using the generated client with default Bearer authentication: 188 189 ```go 190 import ( 191 "os" 192 193 "github.com/go-openapi/strfmt" 194 "github.com/go-openapi/runtime" 195 196 apiclient "github.com/myproject/client" 197 httptransport "github.com/go-openapi/runtime/client" 198 ) 199 200 func main() { 201 r := httptransport.New(apiclient.DefaultHost, apiclient.DefaultBasePath, apiclient.DefaultSchemes) 202 r.DefaultAuthentication = httptransport.BearerToken(os.Getenv("API_ACCESS_TOKEN")) 203 /* 204 r.DefaultMediaType = runtime.XMLMime 205 r.Consumers = map[string]runtime.Consumer{ 206 runtime.XMLMime: runtime.XMLConsumer(), 207 } 208 r.Producers = map[string]runtime.Producer{ 209 "application/xhtml+xml": runtime.XMLProducer(), 210 } 211 */ 212 client := apiclient.New(r, strfmt.Default) 213 214 resp, err := client.Operations.MyGreatEndpoint() 215 if err != nil { 216 log.Fatal(err) 217 } 218 fmt.Printf("%#v\n", resp.Payload) 219 } 220 ``` 221 222 It can under certain circumstances be necessary to manually set the DefaultMediaType and the Consumers and Producers similar to the commented-out code above, particularly if you're using special mime types like `application/xhtml+xml`.