Code Monkey home page Code Monkey logo

angular-swagger-ui's Introduction

angular-swagger-ui

angular-swagger-ui is an angularJS implementation of OpenAPI UI

OpenAPI (aka Swagger) helps you documenting your RESTful API.

OpenAPI UI helps developers discovering your RESTful API by providing an online documentation with an integrated API explorer.

Warning

By default, only OpenAPI 2.0 is supported. To handle OpenAPI 3.0.0 please add module openapi3-converter see Enable OpenAPI 3.0.0. To handle OpenAPI 1.2 please add module swagger1-converter see Enable OpenAPI 1.2. To handle authorization please add module swagger-auth see Enable authorization To handle YAML please add module swagger-yaml-parser see Enable YAML

Demo

A sample app using angular-swagger-ui is available here:

http://orange-opensource.github.io/angular-swagger-ui

Quick Start

Install

npm install angular-swagger-ui

Dependencies

  1. angularJS
  2. bootstrap CSS
  3. angular-ui-bootstrap (required only if using Authorization)

License

All code in this repository is covered by the MIT license. See LICENSE file for copyright details.

Getting Started

Include angular-swagger-ui as a dependency into your application

As some properties of OpenAPI specifications can be formatted as HTML:

  • You SHOULD include ngSanitize as a dependency into your application (avoids JS injection) if OpenAPI specifications are loaded from untrusted sources (see dist/index.html as an example)
  • You CAN add trusted-sources="true" as directive parameter (avoids embedding ngSanitize) if OpenAPI specifications are loaded from trusted sources (see src/index.html as an example)
  • You MUST at least choose one of the two previous solutions
<script type="text/javascript">
	// If directive has parameter trusted-sources="true"
	angular.module('yourApp', ['swaggerUi']);
	...
	// OR if you choosed to use "ngSanitize"
	angular.module('yourApp', ['ngSanitize', 'swaggerUi']);
	...
</script>

Create an HTML element in your angularJS application's template or in your HTML page

<div swagger-ui url="URLToYourOpenAPISpecification" api-explorer="true"></div>

Add swagger-ui.min.js and angular.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<!-- if you choosed to use "ngSanitize" -->
 	<script src="yourPathToAngularSanitize/angular-sanitize.min.js"></script>
</body>

Add swagger-ui.min.css and bootstrap.min.css to the head of the HTML page.

<body>
	<head>
		...
		<link rel="stylesheet" href="yourPathToBootstrapCSS/bootstrap.min.css">
		<link rel="stylesheet" href="yourPathToAngularSwaggerUI/dist/css/swagger-ui.min.css">
  	</head>
</body>

Parameters

API explorer

Display or not API explorer, default is false

<div swagger-ui url="URLToYourOpenAPISpecification" api-explorer="true/false"></div>

OpenAPI specification loading indicator

yourScopeVariable will be assigned to true or false depending on OpenAPI specification loading status

<div ng-show="yourScopeVariable">loading ...</div>
<div swagger-ui url="URLToYourOpenAPISpecification" loading="yourScopeVariable"></div>

Error handler

Define an error handler to catch errors, if none defined console.error is used

<div swagger-ui url="URLToYourOpenAPISpecification" error-handler="yourErrorHandler"></div>
$scope.yourErrorHandler = function(/*String or Object*/ message, /*Integer*/ code){
	
}

Permalinks

Allows having a URL direct access to a group of operations or to an operation and making it unfolded at startup

<div swagger-ui url="URLToYourOpenAPISpecification" permalinks="true/false"></div>

Download

Display or not a link to download swagger file.

<!-- display link with url label -->
<div swagger-ui url="URLToYourOpenAPISpecification" download></div>

<!-- display link with specific key enter in swaggerTranslatorProvider -->
<div swagger-ui url="URLToYourOpenAPISpecification" download="downloadLabel"></div>

OpenAPI validator

Disable OpenAPI validator or define a custom OpenAPI validator. If parameter not defined, the validator will be 'http://online.swagger.io/validator'

<div swagger-ui url="URLToYourOpenAPISpecification" validator-url="false or URL"></div>

Parser type

OpenAPI specification parser is chosen depending on the Content-Type of the specification response. If host serving your OpenAPI specification does not send Content-Type: application/json then you can force the parser to JSON:

<div swagger-ui url="URLToYourOpenAPISpecification" parser="json"></div>

Template URL

Define a custom template to be used by OpenAPIUI

<div swagger-ui url="URLToYourOpenAPISpecification" template-url="yourTemplatePath"></div>

Inherited properties

Allows displaying inherited properties of polymorphic models

<div swagger-ui url="URLToYourOpenAPISpecification" show-inherited-properties="true/false"></div>

Input type and input

Render an OpenAPI specification from JSON object
<div swagger-ui input-type="json" input="yourJsonObject"></div>
Render an OpenAPI specification from YAML string

Make sure to use module swagger-yaml-parser, see Enable YAML

<div swagger-ui input-type="yaml" input="yourYamlString"></div>
Render an OpenAPI specification from URL (same behavior as using "url" parameter)
<div swagger-ui input-type="url" input="yourURL"></div>

i18n

Built-in languages

angular-swagger-ui is available in english and french, english is used by default

To use french, add fr.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/i18/fr.min.js"></script>
</body>

Set language to french at startup

<script type="text/javascript">
	angular
		.module('yourApp', ['swaggerUi'])
		.config(function(swaggerTranslatorProvider) {
			swaggerTranslatorProvider.setLanguage('fr');
		});
	...
</script>

Set language to french at runtime

<script type="text/javascript">
	angular
		.module('yourApp', ['swaggerUi'])
		.controller('yourController', function(swaggerTranslator) {
			swaggerTranslator.useLanguage('fr');
		});
	...
</script>

Add languages

You can add your own languages, see src/scripts/i18n/en.js to find the keys you have to override

<script type="text/javascript">
	angular
		.module('yourApp', ['swaggerUi'])
		.config(function(swaggerTranslatorProvider) {
			swaggerTranslatorProvider.addTranslations('yourLangId', {
				key: 'value'
				...
			});
			swaggerTranslatorProvider.setLanguage('yourLangId');
		});
	...
</script>

Internationalize your app

You can also use swaggerTranslator to internationalize your app by using a service, a directive or a filter

<body>
 	...
 	<div swagger-translate="yourKey" swagger-translate-value="yourParam"></div>
 	<div ng-bind="yourDynamicKey|swaggerTranslate:yourDynamicParam"></div>
 	...
	<script type="text/javascript">
		angular
			.module('yourApp', ['swaggerUi'])
			.config(function(swaggerTranslatorProvider) {
				swaggerTranslatorProvider.addTranslations('en', {
					yourKey: 'blablabla {{propertyNameOfYourParam}}'
					...
				});
			})
			.controller('yourController', function(swaggerTranslator) {
				var localizedMessage = swaggerTranslator.translate('yourKey', yourParam);
			});
		...
	</script>
</body>

Customization

Enable OpenAPI 3.0.0

See OpenAPI 3.0.0 spec. Add openapi3-converter.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/modules/openapi3-converter.min.js"></script>
</body>

Enable authorization

oauth is not implemented, only basic and API key authorizations are implemented. Add swagger-auth.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/modules/swagger-auth.min.js"></script><!-- without angular-ui-bootstrap modal embedded -->
 	OR
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/modules/swagger-auth-ui-boostrap-modal.min.js"></script><!-- angular-ui-bootstrap modal embedded -->
 	...
	<script type="text/javascript">
		angular
			.module('yourApp', ['swaggerUi', 'swaggerUiAuthorization'])
			// what is below is required for oauth2 flows 'implicit' and 'accessCode' (ie. authorizationCode)
			// what is below can also be used to initialize apiKey or Basic authorizations
      .config(function(swaggerUiAuthProvider) {
          swaggerUiAuthProvider.configuration({
              // required for oauth2 flow 'implicit' and 'accessCode' (ie. authorizationCode)
             	redirectUrl: 'yourPathToAngularSwaggerUI/oauth2-redirect.html' 
              // optional
              yourSecurityName: {
              	apiKey: 'yourApiKeyValue' // optional, can be used to initialize api key value
              },
              // optional
              yourSecurityName: {
              	login: 'yourLogin', // optional, can be used to initialize basic login
              	password: 'yourPassword' // optional, can be used to initialize basic password
              },
              // optional
              yourSecurityName: {
              	clientId: 'yourClientId', // optional, can be used to initialize oauth2 credentials
              	clientSecret: 'yourClientSecret', // optional, can be used to initialize oauth2 credentials
              	login: 'yourLogin', // optional, can be used to initialize oauth2 credentials
              	password: 'yourPassword', // optional, can be used to initialize oauth2 credentials
              	scopeSeparator: 'scopeSeparator', // optional, can be used to configure oauth2 scopes separator, default value is space
              	// optional, can be used to configure oauth2 additional query params to tokenUrl and authorizationUrl
              	queryParams: {
              		'yourQueryParamName': 'yourQueryParamValue'
              		...
              	}, 
              },
          });
      })
			...
	</script>
</body>

Enable OpenAPI [aka Swagger] 1.2

See OpenAPI 1.2 spec. Add swagger1-converter.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/modules/swagger1-converter.min.js"></script>
</body>

Enable OpenAPI external references

See OpenAPI 2.0 spec. Add swagger-external-references.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/modules/swagger-external-references.min.js"></script>
</body>

Enable XML formatter on API explorer responses

Add swagger-xml-formatter.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/modules/swagger-xml-formatter.min.js"></script>
</body>

Enable YAML

Add js-yaml library. Add swagger-yaml-parser.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToJsYaml/js-yaml.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/modules/swagger-yaml-parser.min.js"></script>
</body>

Enable markdown

Add marked library. Add swagger-markdown.min.js at the end of the body

<body>
 	...
 	<script src="yourPathToAngularJS/angular.min.js"></script>
 	<script src="yourPathToMarked/marked.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/swagger-ui.min.js"></script>
 	<script src="yourPathToAngularSwaggerUI/dist/scripts/modules/swagger-markdown.min.js"></script>
</body>

Writing your own modules

Modifying angular-swagger-ui can be achieved by writing your own modules. As an example your can have a look at the ones in src/scripts/modules. A module is an object (can be a service) having a function execute which must return a promise.

You can make your module modifying behaviours at different phases:

  • BEFORE_LOAD: allows modifying OpenAPI specification request before it is sent
  • BEFORE_PARSE: allows modifying OpenAPI specification after it has been loaded
  • PARSE: allows adding an OpenAPI parser for content types other than JSON
  • BEFORE_DISPLAY: allows modifying internal parsed OpenAPI specification before it is displayed
  • BEFORE_EXPLORER_LOAD: allows modifying API explorer request before it is sent
  • AFTER_EXPLORER_LOAD: allows modifying API explorer response before it is displayed
angular
	.module('myApp', ['swaggerUi'])
	.service('myModule', function($q) {

		this.execute = function(data) {
			var deferred = $q.defer();
			// if nothing done: call deferred.resolve(false);
			// if success: call deferred.resolve(true);
			// if error: call deferred.reject({message: 'error message', code: 'error_code'});
			return deferred.promise;
		}

	})
	.run(function(swaggerModules, myModule){
		// default priority is 1
		// higher is the priority, sooner the module is executed at the specified phase
		swaggerModules.add(swaggerModules.BEFORE_LOAD, myModule, priority);
	})
	...

angular-swagger-ui's People

Contributors

adematte avatar anil2 avatar borewit avatar ckuhn-finicity avatar claymodel avatar crabl avatar daniel-cotton avatar julianwielga avatar maciejdobrowolski avatar mathieuales avatar randallknutson avatar stephenwelsh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-swagger-ui's Issues

Publish v0.4.0 to npm

For some reason the latest version in npm registry is 0.2.7
Could you publish the latest version there?

Document module name

It should say somewhere in the documentation that you need to include 'swaggerUi' as a dependency in your app in order to use the lib.

Direct references are not resolved

Hello and thanks for the project !

I have a swagger specification with direct references in the response part.
For example :

          "responses": {
          "200": {
            "$ref": "#/responses/ok_myres"
          },
          "400": {
            "$ref": "#/responses/common_400"
          },

ok_myres contains schemas and examples, common_400 only contains a description like that:

    "common_400": {
      "description": "Bad request. Invalid request body or parameters."
    },

It works with swagger-jsdoc and swagger-editor, but I have nothing displayed in the angular-swagger-ui directive.
To make it work, it was necessary to add this code :

                    if (response['$ref']) {
                        response = swaggerModel.resolveReference(swagger, response);
                    }

here in your code for the "ok_myres" reference: https://github.com/Orange-OpenSource/angular-swagger-ui/blob/master/src/scripts/swagger-parser.js#L227

and for the "common_400" reference, this code :
operation.responses[code] = response;
here in your code : https://github.com/Orange-OpenSource/angular-swagger-ui/blob/master/src/scripts/swagger-parser.js#L251

Is it normal ? Do I miss something ? Thanks.

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed (Fix)

Updated to swagger 0.2.1 and I am getting an Error like this:
ngrepeatdupe

Had to change 1 thing in line 665 at /dist/scripts/swagger-ui.js

// parse resources
            if (!swagger.tags) {
                resources.push({
                    name: 'default',
                    open: true
                });
                map['default'] = 0;
            }

to this:

// parse resources
            if (swagger.tags) {
                resources.push({
                    name: 'default',
                    open: true
                });
                map['default'] = 0;
            }

Modifying POST body has no effect

It seems modifying the POST body after sending a request with "Try it out" has no effect. Old body string is sent regardless. Is the body cached somewhere? My angular-swagger-ui version is 0.2.6.

RangeError: Maximum call stack size exceeded Error

image

I'm getting the following error for a rather large set of endpoint definitions. It seems like the code gets stuck in the recursive function until it produces a stack overflow. Any idea how to fix this? Much appreciated!

Bower install does not work

Hi,

Thank you for this nice project (quite nice to integrate our Swagger doc within our angular app) !

Just to let you know: there is still an issue with "bower install" since the retrieved version is not the correct one (seems to be quite old). Your last commit seems to be associated to this issue but does not fix any thing for me...

In addition, do you accept pull request since I have prepared a small enhancement to transform model properties into links ?

Assuming we have the following model:
image
In the "CustomerStub", "contacts" is an array of "Contact" object and now you can click to navigate directly towards this definition in the model (interesting when you have a large model).

the generated HTML looks like this:

  • classes with a <span> and an id attribute:
    <span id="customer:CustomerStub">customer:CustomerStub</span>
  • properties with <a> with href atttribute:
    <a href="#/admin/doc/customer#customer:contact:Contacts">customer:contact:Contacts</a>

This implies to simply pass to the swagger-ui directive a new parameter with route base (#/admin/doc/customer in my example) to be used within href (link within the same page - to avoid any interaction with ui.router).
<div swagger-ui url="swaggerUrl" loading="isLoading" ref-link-base-url="stateUrl" api-explorer="false" permalinks="true" validator-url="false" trusted-sources="true" error-handler="swaggerErrorHandler">

Please let me know if you are interested in reviewing this.
Thanks.

Swagger UI Displays but I get an "ERROR" indicator

My UI displays and it is showing all of my routes. Everything looks great except there is a big red ERROR indicator on the lower right. When I click it I get:

{"schemaValidationMessages":[{"level":"error","message":"Can't read from file /swagger.json"}]}

Obviously if it couldn't read the json file it wouldn't be displaying my documentaion.

discrepancy in secondary tags between Swagger UI and Swagger angular

Secondary tag operations are missing from Swagger Angular, but correctly displayed in Swagger UI.
See json and output bellow.

JSON

{
  "swagger" : "2.0",
  "info" : {
    "description" : "This API.",
    "title" : "This API Specification"
  },
  "tags" : [ {
    "name" : "create user"
  }, {
    "name" : "get user"
  }, {
    "name" : "update user"
  }, {
    "name" : "Admin APIs"
  }, {
    "name" : "Public APIs"
  } ],
  "schemes" : [ "http", "https" ],
  "paths" : {
    "/admin/users/user" : {
      "post" : {
        "tags" : [ "create user", "Admin APIs" ],
        "summary" : "Create user profile (Admin)",
        "operationId" : "createUser (Admin)",
        "consumes" : [ "application/json" ],
        "produces" : [ "application/json" ],
        "parameters" : [ ]
      }
    },
    "/admin/users/user/{id}" : {
      "get" : {
        "tags" : [ "get user", "Admin APIs" ],
        "summary" : "Retrieve user (Admin API).",
        "operationId" : "getUser (Admin)",
        "produces" : [ "application/json" ],
        "parameters" : [ ]
      }
    },
    "/users" : {
      "get" : {
        "tags" : [ "get users", "Public APIs" ],
        "summary" : "Retrieve users in bulk.",
        "operationId" : "getUsers",
        "produces" : [ "application/json" ],
        "parameters" : [ ]
      }
    },
    "/users/user/{id}" : {
      "get" : {
        "tags" : [ "get user", "Public APIs" ],
        "summary" : "Retrieve user.",
        "operationId" : "getUser",
        "parameters" : [ ]
      },
      "put" : {
        "tags" : [ "update user", "Public APIs" ],
        "summary" : "Update user.",
        "operationId" : "updateUser",
        "produces" : [ "application/json" ],
        "parameters" : [ ]
      }
    }
  },
  "definitions" : { }
}

Swagger UI

create user

  • POST /admin/users/user

get user

  • GET /admin/users/user/{id}
  • GET /users/user/{id}

get users

  • GET /users

update user

  • PUT /users/user/{id}

Admin APIs

  • POST /admin/users/user
  • GET /admin/users/user/{id}

Public APIs

  • GET /users
  • GET /users/user/{id}
  • PUT /users/user/{id}

Swagger Angular

create user

  • POST /admin/users/user

get user

  • GET /admin/users/user/{id}
  • GET /users/user/{id}

update user

  • PUT /users/user/{id}

get users

  • GET /users

0.2.7 Archive for Bower still has 0.2.6 version.

Here is package.json content in https://github.com/Orange-OpenSource/angular-swagger-ui/releases/tag/0.2.7:

{
"name": "angular-swagger-ui",
"version": "0.2.6",
"dependencies": {},
"devDependencies": {
"glob": "^4.3.5",
"grunt": "^0.4.5",
"grunt-concurrent": "^1.0.0",
"grunt-contrib-clean": "^0.6.0",
"grunt-contrib-concat": "^0.5.0",
"grunt-contrib-connect": "^0.9.0",
"grunt-contrib-copy": "^0.7.0",
"grunt-contrib-jshint": "^0.11.0",
"grunt-contrib-less": "^1.0.0",
"grunt-contrib-uglify": "^0.9.2",
"grunt-contrib-watch": "^0.6.1",
"grunt-html2js": "^0.3.0",
"grunt-newer": "^1.1.0",
"jshint-stylish": "^1.0.0",
"load-grunt-tasks": "^3.0.0",
"matchdep": "^0.3.0",
"time-grunt": "^1.0.0"
},
"engines": {
"node": ">=0.10.0"
}
}

How to you pass authorization tokens

Hi

I have auth token that need to be passed as header "X-Auth-Token" for each request. How do I pass that in the swagger definition json file?

angular version

Could you relax the angular version that is required a little? People tend to use 1.4.x right now and bowers resolution warnings are a real pain when you're building in a CI environment...

Thanks and Cheers!

The swagger1-to-swagger2-converter fails to create models with references

If a swagger 1.X specification contains a model with objects that contain references to other objects in the model, the referenced objects are not handled properly. The problem is located in lines 184-190 of the script, where the type property is being used instead of the $ref one, so the code should probably be changed to be something like the one below, which works fine for me:

if (swagger1.models && swagger1.models[prop.$ref]) {
  prop.$ref = '#/definitions/' + prop.$ref;
  //delete prop.type; // Not quite sure what this line is for?
}
if (prop.items && swagger1.models && swagger1.models[prop.items.$ref]) {
  prop.items.$ref = '#/definitions/' + prop.items.$ref;
  //delete prop.items.type; // Not quite sure what this line is for?
}

Thanks.

Regards

Lars

There should be callback when "explore" is finished

Hi,
I am using multiple groups of API on server side.
On UI I've prepared buttons to switch between them easily.
I would like to display rotating spinner during reload process - that's easy - and hide it when explore completed refresh.
It would be nice to have attribute where I could specify custom callback function which would be called from directive when reload is completed.

Best regards

Generating the API documentation for a valid JSON

why can't i generate the documentation if i put a valid url for a valid JSON caught from github for example? the only valid URL is the petStore URL, could you make it possible to generate the documentation for any valid JSON?

Uncaught Error: [$injector:modulerr] when importing 'swaggerUi'

When I add swaggerUi to angular module, I get the $injector:modulerr error in Chrome dev console. My import statement is the following:

var app = angular.module('flapperNews', ['ui.router','elasticsearch','swaggerUi'],['$locationProvider', function($locationProvider) { $locationProvider.html5Mode({ enabled: true }); }]).config(function($provide) { $provide.decorator('$sniffer', function($delegate) { $delegate.history = false; return $delegate; }); });

I've run bower install angular-swagger-ui and have included it in the <head> tag of my index.html file. Has anyone run into this issue? I don't know what more I can do.

Unable to "Try it out" and click to set parameter as body

Hi, I have faced strange behaviour while integrating angular-swagger-ui into my project.
Button "Try it out" is missing - neither for my API and http://petstore.swagger.io/v2/swagger.json.
Also field input for body or parameter is missing.

It fails on both Firefox and Chrome.

In browser console I can see for both cases correctly swagger object. Also there is a lot of print for schema.type like "array" and "undefined". As last is printed resources as Array of objects.

I'm using WebJars packages:
angular-swagger-ui 0.1.3

Could you help me with that?

UI thread being blocked

Hi,

I'm loading in swagger json that has been stored in a DB (so not loading from a URL, but passing in a JSON object); for larger Swagger JSON objects angular-swagger-ui needs a couple of seconds to parse all the data, during which the UI thread gets blocked, resulting in a poor user experience

Is anybody else seeing this behaviour, and if so, can this be remedies somehow (maybe by using web workers)?

CSS in bower.json

CSS should be defined in bower.json so you don't have to manually import it.

Custom template?

It would be nice to be able to pass a optional template URL to the directive.
On another hand, I guess that's where most of the time saving are done using this lib, not having to style the response.

Translator

lang/translator.js (original swagger-ui) not working with this solution

is there a way to activate it?

Adding Basic Auth

Trying to get Basic Auth going.

Approach 1

Based on here and this, I added a transform:

...
<form name="urlForm" ng-submit="swaggerUrl=url" class="form-inline">
    <input type="text" placeholder="username" class="form-control" id="username" name="username" ng-model="username" required>
    <input type="password" placeholder="password" class="form-control" id="password" name="password" ng-model="password" required>
</form>
...

<div swagger-ui url="swaggerUrl" loading="isLoading" api-explorer="true" api-explorer-transform="addAuthorization" trusted-sources="true" error-handler="myErrorHandler" permalinks="true"></div>

...
 angular.module('myApp', ['swaggerUi'])
.controller('MyCtrl', function ($scope, swaggerTranslator) {
                // init form
                $scope.isLoading = false;
                $scope.url = $scope.swaggerUrl = 'http://localhost:14174/swagger/docs/v1';
                $scope.myErrorHandler = function (data, status) {
                    alert(swaggerTranslator.translate('error', {
                        message: data,
                        code: status
                    }));
                };

                $scope.setEn = function () {
                    swaggerTranslator.useLanguage('en');
                };
                $scope.getLang = function () {
                    return swaggerTranslator.language();
                };

                $scope.addAuthorization = function addAuthorization(request) {
                    console.log('test');
                    request.headers.Authorization = 'Basic ' + btoa($scope.username + ':' + $scope.password);
                };
            });

but addAuthorization is never called.

Approach 2:

Going the module way:

angular.module('myApp', ['swaggerUi'])
.service('myModule', function ($q) {

                this.execute = function (req) {
                    var deferred = $q.defer();
                    req.headers.Authorization = 'Basic ' + btoa(document.getElementById('username').value + ':' + document.getElementById('password').value);
                    deferred.resolve(true);
                    return deferred.promise;
                }

            })
            .run(function (swaggerModules, myModule) {
                swaggerModules.add(swaggerModules.BEFORE_EXPLORER_LOAD, myModule);
            });

The only oddity here is the document.getElementById calls. Is this the way to go?

Server rejectes as Unsupported media type because Content-Type is missing for POST

Hi,
I've checked version 0.1.3 and 0.1.6 and in both have the same problem.
When using try-it-out button for POST or PUT request is send but Content-Type and body are missing (checked on both client and server).
In result server rejects request with status HTTP 415 Unsupported media type.

I tried to force Content-Type to be application/json using custom transform like:

if (request.method === 'post'
        || request.method === 'put') {
   request.headers['Content-Type'] = 'application/json';
}

But it didn't help at all. While actually overriding Authorization works as expected.
Code compliant with version 0.1.6 looks like that:

<div swagger-ui=""
     url="swaggerUrl"
     api-explorer="true"
     error-handler="myErrorHandler"
     transform-request="myTransform"
     try-it="true">
</div>
(function () {
   'use strict';

   angular
           .module('appraisalOnlineApp')
           .controller('DocumentationApiCtrl', DocumentationApiCtrl);

   DocumentationApiCtrl.$inject = ['$scope', 'toaster', 'logToServerUtil'];

   function DocumentationApiCtrl($scope, toaster, logToServerUtil) {
      $scope.businessApi = 'v2/api-docs?group=Business-API';
      $scope.adminApi = 'v2/api-docs?group=Admin-API';
      $scope.authorization = 'blabla';
      $scope.myErrorHandler = myErrorHandler;
      $scope.myTransform = myTransform;
      $scope.switchApi = switchApi;

      // init form
      switchApi($scope.businessApi);

      //////////

      function switchApi(api) {
         $scope.url = api;
         $scope.swaggerUrl = api;
      }
      // error management
      function myErrorHandler(data, status) {
         logToServerUtil.error('Load Swagger documentation failure', status);
         toaster.pop('error', null, 'documentation/api/load-failure', null, 'template');
      }
      // transform API explorer requests
      function myTransform(request) {
         console.log('request', request);
         if (request.method === 'post'
                 || request.method === 'put') {
            console.log('yes sir');
            request.headers['Content-Type'] = 'application/json';
         }
         request.headers['Authorization'] = $scope.authorization;
      }
   }
})();

Basepath Problem

This issue is about swagger spec and base path behavior.
Using this library if you set it to "/" (meaning root), it's appending a "/" to the end of the url resulting in http(s)://host:port/apiRoute//... it should be http(s)://host:port/apiRoute/...
Instead if it's not simply "/", and something like "/basepath/" it's correct to append a "/" on the end if it doesn't exist.
I don't have this issue with swagger-ui itself, hence I though I should bring it up.

Enum values are treated as Objects

Enum values are rendered and treated as objects.

Eg:

"definitions":{
   "Gender" : {
      "enum" : ["Male", "Female"],
      "type" : "string",
      "title" : "Gender"
   },
   "Person" : {
      "type" : "object",
      "title" : "Person",
      "properties":{
            "gender":{
                "$ref" : "#/definitions/Gender"             
        }
      }
   }
}

When this is rendered and the object is generated for person, enum property is being rendered as:

{
   "gender":{}
}

Instead, they should be displayed as:

{
   "gender":"string"
}

Documentation

Hi! Are there any plans to write documentation with some basic examples of usage?

Incorrect Base URL and Host for 1.2 swagger

I need to build an app to explore this 1.2 version of swagger. Because the swagger host doesn't support CORS, I wrote a proxy to proxy the swagger to my app (say running on localhost). The rendering works fine, but Try it out failed because of the host and BASE URL:

[BASE URL: https://api.bcdevexchange.org:443/OPEN511/1.0.0, API VERSION: 1.0.0, HOST: http://localhost]

The swagger doesn't have Host property but basePath is set to full URL at resource API declaration level. Apparently here API Host is incorrectly assumed to be the swagger host. Instead, it should use basePath without prepending Host because basePath contains host as specified by 1.2 swagger

Seems like "allOf" and "multipleOf" options are ignored.

I have a following model schema:

# this file is exposed and passed to angular-swagger-ui in JSON format

  ModifiableModelMixin:
    type: object
    properties:
      createdAt:
        type: string
        format: date
      updatedAt:
        type: string
        format: date

  Client:
    type: object
    properties:
      clientId:
        type: string
      clientName:
        type: string
      customFields:
        type: object

  GetClientData:
    type: object
    allOf:
      - $ref: '#/definitions/ModifiableModelMixin'
      - $ref: '#/definitions/Client'
    properties:
      propA:
        $ref: '#/definitions/propA'
      propB:
        $ref: '#/definitions/propB'

But in the UI only 'propA' and 'propB' are rendered as properties of GetClientData.

Internationalization dir for rtl languages

Hello,
I tried to implement arabic language, and as it's written from right to left (rtl), I wanted to add the dir attribute(="rtl") to the swagger-ui directive.
In fact, I switch the dir attribute value according to the language selected.
Almost works !
Elements are rendered from right to left except that:
1 - Resource Names (from tags) remain in the left part
2 - Vertical Lines remain to the right of the commands

These 2 points are the main ones, for the second , it's related to these css rules:
(sorry I looked directly at the css file generated, not in the less files)
.swagger-ui .endpoint .endpoint-actions li {
border-right: 1px solid #ddd;
}
.swagger-ui .endpoint .endpoint-actions li:last-child {
border-right: 0;
}

So if I want to make it work, I need to add:
[dir='rtl']
.swagger-ui .endpoint .endpoint-actions li {
border-left: 1px solid #ddd;
}
.swagger-ui .endpoint .endpoint-actions li:last-child {
border-left: 0;
}

or :)
[dir='rtl']
.swagger-ui .endpoint .endpoint-actions li:first-child {
border-right: 0;
}

Will you deal with these kind of internationalization issues in the next release ?
You told me that the direct references will be fixed with the next release, do you know about when it will be ready ?
Either I can use template-url for my internationalization problem and swaggerModules.PARSE for direct references, but I'd prefer not to add too much code, especially if I only change a few lines.
Thanks a lot !

Implemented JSON request forms

Hi,

I forked your repo and I've been working on replacing body text areas with form for JSON payloads for a personal project. It still needs some work but you can check it out here http://plnkr.co/QAS5gj.

If you find it useful I'm available to make any necessary changes for a merge.

Cheers

If swagger.host / basePath is not specified, it should use the right default

the proper default is use the relative location from the swagger url.

i.e. if you run swagger-ui on http://swagger-ui:8000/ and your swagger url is http://swagger-definition:10000/myapp/swagger.json, it should resolve to

swagger.host = swagger-definition:10000
swagger.basePath = /myapp

currently it resolves to

swagger.host = swagger-ui
swagger.basePath =

which is not inline with swagger-ui code.

For the second case, if you run swagger-ui on http://swagger-ui:8000/ and your swagger url is /myapp/swagger.json, it should resolve to

swagger.host = swagger-ui:8000
swagger.basePath = /myapp

how to expose Try it out!! functionality?1

I integrated Swagger Ui in my app and i need to expose the functionality of "Try it out" button. I need to use it in two different ways:
1- the functionality the way you did which is working fine.
2- the second way is to make it call an API that i made that will return : result : true and data: true in some conditions.
you use to have a support for this code:
transform try it request

$scope.myTransform = function(request){
    request.headers['api_key'] = 's5hredf5hy41er8yhee58';
};

Is there a way to do it in this version? like i can do with the input type (json string, yaml string or a url etc.)

XML special characters

Hi,

If I want to add xml special characters like >, how can I do?

I tried writing & gt; (without the space) in the xml but not works.

Thanks you! great lib!

Incorrect handling of parameters on Path Item Object

When a swagger 2.0 definition is parsed with parameters on a Path Item Object (See: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#path-item-object)

"/apis/{apiId}": {
    "parameters": [{
        "$ref": "#/parameters/apiId"
    }],
    "get": {
        "description": "Get details of an API",
        "parameters": [{
            "$ref": "#/parameters/Accept"
        }, {
            "$ref": "#/parameters/If-None-Match"
        }, {
            "$ref": "#/parameters/If-Modified-Since"
        }]
    }
}

duplicate operations are created:
operations
and it's also not possible to use the "global" parameters in the "Try it out" call.

Href in templates result in CSP warning

I'm having trouble with the templates in our application.
Our application has a content security policy(CSP) enabled that does not allow inline javascript.
The templates used in this UI contain elements which have an href to "javascript:;".
This results in a CSP warning in our application every time we click a link in the swagger UI.

Is it possible to have the library updated with a CSP friendly version which does not contain this behavior?

The latest version (0.2.5) is broken

With 0.2.5, the operation section does not show up. It only shows

GET   /blah/blah

with 0.2.4, it shows

GET /blah/blah
response class (status 200).....
response content type
try it out....

Relative Pathing

I see that relative pathing is not yet supported.

And I see this in swagger-ui.js...
//FIXME should use server hosting the documentation if scheme or host are not defined

Is there any immediate plan to do this?
I could contribute to this if you need assistance.

can't test my APIs

i integrated the ui into my dashboard and i am getting the yml file from github.
The UI is giving the documentation but i can't add the params to test my API and even the try it out button isn't showing.
Any idea about this problem?
Kindly check the attached picture for a clearer idea.
screen shot 2017-01-15 at 10 05 40 pm

Where should I add reloadOnSearch?

I saw a warning saying that
AngularSwaggerUI: when using permalinks you should set reloadOnSearch=false in your route config to avoid UI being rebuilt multiple times

However, I'm not sure where and how should I add reloadOnSearch=false. Could you please let me know?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.