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