UNPKG

10.4 kBMarkdownView Raw
1# Swagger Client <img src="https://raw.githubusercontent.com/swagger-api/swagger.io/wordpress/images/assets/SW-logo-clr.png" height="50" align="right">
2
3[![Build Status](https://travis-ci.org/swagger-api/swagger-js.svg?branch=master)](https://travis-ci.org/swagger-api/swagger-js)
4
5**Swagger Client** is a JavaScript module that allows you to fetch, resolve, and interact with Swagger/OpenAPI documents.
6
7## New!
8
9**This is the new version of swagger-js, 3.x.** The new version supports Swagger 2.0 as well as OpenAPI 3.
10
11 Want to learn more? Check out our [FAQ](https://github.com/swagger-api/swagger-js/blob/master/docs/MIGRATION_2_X.md).
12
13For the older version of swagger-js, refer to the [*2.x branch*](https://github.com/swagger-api/swagger-js/tree/2.x).
14
15
16## Note:
17The npm package is called `swagger-client` and the GitHub repository is `swagger-js`.
18We'll be consolidating that soon. Just giving you the heads up. You may see references to both names.
19
20### Usage
21
22##### Prerequisites
23- Runtime:
24 - browser: es5 compatible. IE11+
25 - node v4.x.x
26- Building
27 - node v6.x.x
28
29##### Download via npm
30
31```
32npm install swagger-client
33```
34
35##### Import in code
36
37```javascript
38import Swagger from 'swagger-client'
39// Or commonjs
40const Swagger = require('swagger-client')
41```
42
43##### Import in browser
44
45```html
46<script src='//unpkg.com/swagger-client' type='text/javascript'></script>
47<script>
48var swaggerClient = new SwaggerClient(specUrl);
49</script>
50```
51
52
53#### API
54
55This lib exposes these functionalities for Swagger 2.0 and OpenAPI 3:
56
57- Static functions for...
58 - HTTP Client
59 - Document Resolver (monolithic & subtree)
60 - TryItOut Executor
61- A constructor with the methods...
62 - HTTP Client, for convenience
63 - Document Resolver, which will use `url` or `spec` from the instance
64 - TryItOut Executor, bound to the `http` and `spec` instance properties
65 - Tags Interface, also bound to the instance
66
67HTTP Client
68-----------
69
70`Swagger.http(req)` exposes a [Fetch-like interface](https://github.com/lquixada/cross-fetch) with a twist: allowing `url` in the request object so that it can be passed around and mutated. It extends Fetch to support request and response interceptors and performs response & header serialization. This method could be overridden to change how SwaggerJS performs HTTP requests.
71
72```js
73// Fetch-like, but support `url`, `query` and `xxxInterceptor`
74const request = {
75 url,
76 query,
77 method,
78 body,
79 headers,
80 requestInterceptor,
81 responseInterceptor,
82 userFetch
83}
84
85Swagger.http(request)
86 .then((res) => {
87 res.statusCode // status code
88 res.statusText // status text, ie: "Not Found"
89 res.body // JSON object or undefined
90 res.obj // same as above, legacy
91 res.text // textual body, or Blob
92 res.headers // header hash
93 })
94 .catch((err) => {
95 err // instanceof Error
96 err.response // response or null
97 })
98
99// Interceptors
100Swagger.http({
101 requestInterceptor: (req: Request) => Request | Promise<Request>
102 responseInterceptor: (res: Response) => Response | Promise<Response>
103})
104
105// Custom Fetch
106Swagger.http({
107 userFetch: (url: String, options: Object) => Promise
108})
109
110```
111
112Swagger Specification Resolver
113---------------------
114
115`Swagger.resolve({url, spec, http})` resolves `$ref`s (JSON-Refs) with the objects they point to.
116
117```js
118
119Swagger.resolve({url, spec, http}).then((resolved) => {
120 resolved.errors // resolution errors, if any
121 resolved.spec // the resolved spec
122})
123```
124> This is done automatically if you use the constructor/methods
125
126TryItOut Executor
127-----------------
128An HTTP client for OAS operations, maps an operation and values into an HTTP request.
129
130```js
131const params = {
132 spec,
133
134 operationId, // Either operationId, or you can use pathName + method
135 (pathName),
136 (method),
137
138 parameters, // _named_ parameters in an object, eg: { petId: 'abc' }
139 securities, // _named_ securities, will only be added to the request, if the spec indicates it. eg: {apiKey: 'abc'}
140 requestContentType,
141 responseContentType,
142
143 (http), // You can also override the HTTP client completely
144 (userFetch), // Alternatively you can just override the fetch method (if you want to use request.js or some other HttpAgent)
145}
146
147// Creates a request object compatible with HTTP client interface.
148// If `pathName` and `method`, then those are used instead of operationId. This is useful if you're using this dynamically, as `pathName` + `method` are guarenteed to be unique.
149const res = Swagger.execute({...params})
150
151// You can also generate just the request ( without executing... )
152const req = Swagger.buildRequest({...params})
153```
154
155Constructor and methods
156-----------------------
157
158Resolve the spec and expose some methods that use the resolved spec:
159
160- `Swagger(url, opts): Promise`
161- Exposes tags interface (see above)
162- Exposes the static functions: `execute`, `http`, `resolve` and some other minor ones
163- Exposes `#http`, `#execute` and `#resolve` bound to the instance
164
165```javascript
166Swagger('http://petstore.swagger.io/v2/swagger.json')
167 .then( client => {
168 client.spec // The resolved spec
169 client.originalSpec // In case you need it
170 client.errors // Any resolver errors
171
172 // Tags interface
173 client.apis.pet.addPet({id: 1, name: "bobby"}).then(...)
174
175 // TryItOut Executor, with the `spec` already provided
176 client.execute({operationId: 'addPet', parameters: {id: 1, name: "bobby") }).then(...)
177 })
178
179```
180
181Tags Interface
182--------------
183A client for operations. We're currently using the `apis[tag][operationId]:ExecuteFunction` interface, which can be disabled entirely using `Swagger({disableInterfaces: true})` if you don't need it.
184
185OperationId's are meant to be unique within spec, if they're not we do the following:
186- If a tag is absent, we use `default` as the internal tag
187- If an operationId is missing, we deduce it from the http method and path, i.e. `${method}${path}`, with non-alphanumeric characters escaped to `_`. See these tests ([1](https://github.com/swagger-api/swagger-js/blob/7da5755fa18791cd114ecfc9587dcd1b5c58ede1/test/helpers.js#L7), [2](https://github.com/swagger-api/swagger-js/blob/7da5755fa18791cd114ecfc9587dcd1b5c58ede1/test/helpers.js#L77)) for examples.
188- If an operationId is duplicated across all operationIds of the spec, we rename all of them with numbers after the ID to keep them unique. You should not rely on this, as the renaming is non-deterministic. See [this test](https://github.com/swagger-api/swagger-js/blob/7da5755fa18791cd114ecfc9587dcd1b5c58ede1/test/helpers.js#L127) for an example.
189
190```js
191Swagger({ url: "http://petstore.swagger.io/v2/swagger.json" }).then((client) => {
192 client
193 .apis
194 .pet // tag name == `pet`
195 .addPet({ // operationId == `addPet`
196 id: 1,
197 body: {
198 name: "bobby",
199 status: "available"
200 }
201 })
202 .then(...)
203})
204```
205
206If you'd like to use the operationId formatting logic from Swagger-Client 2.x, set the `v2OperationIdCompatibilityMode` option:
207
208```js
209Swagger({
210 url: "http://petstore.swagger.io/v2/swagger.json",
211 v2OperationIdCompatibilityMode: true
212}).then((client) => {
213 // do things as usual
214})
215```
216
217#### OpenAPI 3.0
218
219OpenAPI 3.0 definitions work in a similar way with the tags interface, but you may need to provide additional data in an `options` object for server variables and request bodies, since these items are not actual parameters:
220
221```js
222Swagger({...}).then((client) => {
223 client
224 .apis
225 .pet // tag name == `pet`
226 .addPet({ // operationId == `addPet`
227 id: 1
228 }, {
229 requestBody: {
230 name: "bobby",
231 status: "available"
232 },
233 server: "http://petstore.swagger.io/{apiPrefix}/", // this should exactly match a URL in your `servers`
234 serverVariables: {
235 apiPrefix: "v2"
236 }
237 })
238 .then(...)
239})
240```
241
242In Browser
243----------
244
245If you need activate CORS requests, just enable it by `withCredentials` property at `http`
246
247```html
248<html>
249<head>
250<script src='//unpkg.com/swagger-client' type='text/javascript'></script>
251<script>
252
253var specUrl = 'http://petstore.swagger.io/v2/swagger.json'; // data urls are OK too 'data:application/json;base64,abc...'
254SwaggerClient.http.withCredentials = true; // this activates CORS, if necessary
255
256var swaggerClient = new SwaggerClient(specUrl)
257 .then(function (swaggerClient) {
258 return swaggerClient.apis.pet.addPet({id: 1, name: "bobby"}); // chaining promises
259 }, function (reason) {
260 console.error("failed to load the spec" + reason);
261 })
262 .then(function(addPetResult) {
263 console.log(addPetResult.obj);
264 // you may return more promises, if necessary
265 }, function (reason) {
266 console.error("failed on API call " + reason);
267 });
268</script>
269</head>
270<body>
271 check console in browser's dev. tools
272</body>
273</html>
274
275```
276
277
278Compatibility
279-------------
280
281SwaggerJS has some legacy signature _shapes_.
282
283### Execute
284##### Response shape
285```js
286// swagger-js
287{
288 url,
289 method,
290 status,
291 statusText,
292 headers,
293
294 data, // The textual content
295 obj // The body object
296}
297
298// New shape
299{
300 url,
301 method,
302 status,
303 statusText,
304 headers, // See note below regarding headers
305
306 text, // The textual content
307 body, // The body object
308}
309```
310
311##### Serializing Headers
312
313By default the instance version of `#http` serializes the body and headers.
314However, headers pose an issue when there are multiple headers with the same name.
315As such we've left the static version of `http` to not perform any serialization.
316
317### Build
318
319```sh
320npm install
321npm run test # run test
322npm run test:unit:watch # run test with change watching
323npm run test:lint # run lint
324npm run build # package to release
325npm run build:umd:watch # package with non-minified dist/index.js (for debugging)
326npm run build:bundle # build browser version available at .../browser/index.js
327```
328
329# Migration from 2.x
330
331There has been a complete overhaul of the codebase.
332For notes about how to migrate coming from 2.x,
333please see [Migration from 2.x](docs/MIGRATION_2_X.md)
334
335## Security contact
336
337Please disclose any security-related issues or vulnerabilities by emailing [security@swagger.io](mailto:security@swagger.io), instead of using the public issue tracker.
338
339### Graveyard
340
341For features known to be missing from 3.x please see [the Graveyard](docs/GRAVEYARD.md)
342