简体   繁体   中英

swagger-ui response example as reference in definitions

Is there a way to define a response example object in the 'definitions' and reference it using "$ref" : "#/definitions/ResponseExample"?

This is what my response looks like at the moment:

"200": {
    "description" :"Successful operation",
    "schema" : {
        "$ref" : "#/definitions/AttributesBasicResponse"
    },
    "examples": {
        "application/json": {
            "data": [
                {
                    "name" :"My data",
                    "code": "DATA",
                    "units": "UK, US, EU"
                }
            ],
            "attribute": "test"
        }
    }
}

What I'm trying to achieve is this:

"200": {
    "description" :"Successful operation",
    "schema" : {
        "$ref" : "#/definitions/AttributesBasicResponse"
    },
    "examples": {
        "$ref": "#/definitions/AttributeBasicExample"
    }
}

I've decided to use whitlockjc/json-refs to resolve JSON references before passing json object into swaggerUI.

Load swagger.json using jQuery.get , run JsonRefs.resolveRefs to resolve 'relative' references in this case and then pass resolved json into swaggerUi.setOption('spec', json) and update swaggerUi.load()

This is done on browser side, I could do this on server side using nodejs to reduce the number of http requests.

Updated swagger-ui index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" />
    <link href='css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='css/print.css' media='print' rel='stylesheet' type='text/css'/>
    <script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script>
    <script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
    <script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
    <script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
    <script src='lib/handlebars-2.0.0.js' type='text/javascript'></script>
    <script src='lib/underscore-min.js' type='text/javascript'></script>
    <script src='lib/backbone-min.js' type='text/javascript'></script>
    <script src='swagger-ui.js' type='text/javascript'></script>
    <script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>
    <script src='lib/jsoneditor.min.js' type='text/javascript'></script>
    <script src='lib/marked.js' type='text/javascript'></script>
    <script src='lib/swagger-oauth.js' type='text/javascript'></script>

    <script src='lib/json-refs-standalone.js' type='text/javascript'></script>

    <script type="text/javascript">
        $(function () {
            var url = window.location.search.match(/url=([^&]+)/);
            if (url && url.length > 1) {
                url = decodeURIComponent(url[1]);
            } else {
                url = "http://petstore.swagger.io/v2/swagger.json";
            }
            // Pre load translate...
            if(window.SwaggerTranslator) {
                window.SwaggerTranslator.translate();
            }
            window.swaggerUi = new SwaggerUi({
                url: url,
                dom_id: "swagger-ui-container",
                supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
                onComplete: function(swaggerApi, swaggerUi){
                    if(typeof initOAuth == "function") {
                        initOAuth({
                            clientId: "your-client-id",
                            clientSecret: "your-client-secret-if-required",
                            realm: "your-realms",
                            appName: "your-app-name",
                            scopeSeparator: ",",
                            additionalQueryStringParams: {}
                        });
                    }
                    if(window.SwaggerTranslator) {
                        window.SwaggerTranslator.translate();
                    }
                    $('pre code').each(function(i, e) {
                        hljs.highlightBlock(e)
                    });
                    addApiKeyAuthorization();
                },
                onFailure: function(data) {
                    log("Unable to Load SwaggerUI");
                },
                docExpansion: "none",
                jsonEditor: false,
                apisSorter: "alpha",
                defaultModelRendering: 'schema',
                showRequestHeaders: false
            });

            function changedBaseUrl( event ) {
                event.preventDefault();

                var url = $(this ).val();

                $.get( url ,function(response){
                    // do the json-refs first
                    JsonRefs.resolveRefs( response, { relativeBase: '/swagger',filter: [ 'relative' ] } )
                        .then(function( response ){
                            var json = response.resolved;

                            window.swaggerUi.setOption('spec', json);
                            window.swaggerUi.load();

                            // resolve failed
                        }, function( error ){
                            console.log("failure", error);
                        });
                });
            }

            function addApiKeyAuthorization(){
                var key = encodeURIComponent($('#input_apiKey')[0].value);
                if(key && key.trim() != "") {
                    var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
                    window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
                    log("added key " + key);
                }
            }
            $('#input_baseUrl').change(changedBaseUrl);
            $('#input_apiKey').change(addApiKeyAuthorization);
            // if you have an apiKey you would like to pre-populate on the page for demonstration purposes...
            /*
             var apiKey = "myApiKeyXXXX123456789";
             $('#input_apiKey').val(apiKey);
             */

            window.swaggerUi.load();

            function log() {
                if ('console' in window) {
                    console.log.apply(console, arguments);
                }
            }
        });
    </script>
</head>

<body class="swagger-section">
<div id='header'>
    <div class="swagger-ui-wrap">
        <a id="logo" href="http://swagger.io">swagger</a>
        <form id='api_selector'>
            <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
            <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
            <div class='input'><a id="explore" href="#" data-sw-translate>Explore</a></div>
        </form>
    </div>
</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

Sample swagger.json :

{
    "swagger": "2.0",
    "info": {
        "title": "Basic Login",
        "version": " 1.0.0"
    },
    "paths": {
        "login": {
            "post": {
                "summary": "User login",
                "tags" : [ "Login" ],
                "responses" : {
                    "200": {
                        "description" :"Returns authorization hash",
                        "schema" : {
                            "$ref" : "./schemas/login.json"
                        },
                        "examples": {
                            "$ref": "./responses/login/login.json"
                        }
                    }
                }
            }
        }
    }
}

schema login.json

{
    "type" : "object",
    "properties": {
        "data": {
            "type": "object",
            "properties": {
                "auth_hash": {
                    "type": "string"
                }
            }
        }
    }
}

example login.json :

{
    "data": {
        "auth_hash": "e2ad8410efa2d68cedad76b83eb97ecd"
    }
}

end result after JsonRefs has run:

{
    "swagger": "2.0",
    "info": {
        "title": "Basic Login",
        "version": " 1.0.0"
    },
    "paths": {
        "login": {
            "post": {
                "summary": "User login",
                "tags": [
                    "Login"
                ],
                "responses": {
                    "200": {
                        "description": "Returns authorization hash",
                        "schema": {
                            "type": "object",
                            "properties": {
                                "data": {
                                    "type": "object",
                                    "properties": {
                                        "auth_hash": {
                                            "type": "string"
                                        }
                                    }
                                }
                            }
                        },
                        "examples": {
                            "data": {
                                "auth_hash": "e2ad8410efa2d68cedad76b83eb97ecd"
                            }
                        }
                    }
                }
            }
        }
    }
}

Other references used:

  1. swagger-ui issue #1110
  2. json-refs API docs
  3. json-refs browser source code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM