swagger-ui response example as reference in definitions - javascript

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> </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:
swagger-ui issue #1110
json-refs API docs
json-refs browser source code

Related

Connect a smart contract to HTML code via javascript

I'm trying to follow this example to build a webpage that can interact with a smart contract.
It uses this code in remix:
pragma solidity ^0.4.18;
contract Coursetro {
string fName;
uint age;
function setInstructor(string _fName, uint _age) public {
fName = _fName;
age = _age;
}
function getInstructor() public constant returns (string, uint) {
return (fName, age);
}
}
And this code which I have set up in visual studio code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="main.css">
<!-- <script src="./node_modules/web3/dist/web3.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js#1.0.0-beta.36/dist/web3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Coursetro Instructor</h1>
<h2 id="instructor"></h2>
<label for="name" class="col-lg-2 control-label">Instructor Name</label>
<input id="name" type="text">
<label for="name" class="col-lg-2 control-label">Instructor Age</label>
<input id="age" type="text">
<button id="button">Update Instructor</button>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
web3.eth.defaultAccount = web3.eth.accounts[0];
var CoursetroContract = web3.eth.contract([
{
"constant": false,
"inputs": [
{
"name": "_fName",
"type": "string"
},
{
"name": "_age",
"type": "uint256"
}
],
"name": "setInstructor",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getInstructor",
"outputs": [
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]);
var Coursetro = CoursetroContract.at('0x0CF6A859635A0729d14b524d05619c7162A102bd');
console.log(Coursetro);
Coursetro.getInstructor(function(error, result){
if(!error)
{
$("#instructor").html(result[0]+' ('+result[1]+' years old)');
console.log(result);
}
else
console.error(error);
});
$("#button").click(function() {
Coursetro.setInstructor($("#name").val(), $("#age").val());
});
</script>
</body>
</html>
When I try to pull it up on the local host I've set it up on. localhost:8545, it gives me a 400 Bad Request with this in the console:
So I tried using an http-server command which successfully set up a site I can visit, but I am receiving these errors in the console:
Just wondering if anyone has had this issues before and knows how to fix them? Or if there is something I've missed and that's why I'm getting the errors.

JTable Not Populated

My table is loading with no data...this is how I have the javascript set-up to handle it....
<script type="text/javascript">
$(document).ready(function () {
$('#btnEmployeeTableLoad').click(function () {
$('#EmployeeTable').jtable({
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'employeeName ASC',
actions: {
listAction: 'https://localhost:44328/api/employee-information',
//deleteAction: '/Home/DeletePerson',
//updateAction: '/Home/UpdatePerson',
//createAction: '/Home/CreatePerson'
},
fields: {
employeeName: {
title: 'employeeName',
width: '35%'
},
employeeAddress: {
title: 'employeeAddress',
width: '15%'
},
employeeManager: {
title: 'employeeManager',
width: '15%'
},
prevExperience: {
title: 'prevExperience',
width: '15%'
}
}
});
$('#EmployeeTable').jtable('load');
});
});
</script>
both my ListData and ListData.Count show 752 rows so I know the data is being retreived from server
return Json(new { Result = "OK", Records = ListData, TotalRecordCount = ListData.Count });
EDIT
This is what the Network tab shows in my browser:
{result: "OK",…}
records: [{employeeName: "Employee Name 1", employeeAddress: "Test Address 1", employeeManager: "Test Manager 1", prevExperience: "No"},…]
result: "OK"
totalRecordCount: 757
EDit 2
These are the libraries i'm including
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"></style>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.0/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.print.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jtable#2.6.0/lib/jquery.jtable.min.js"></script>
<link href="https://cdn.datatables.net/buttons/1.6.0/css/buttons.dataTables.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/jtable#2.6.0/lib/themes/metro/blue/jtable.css" rel="stylesheet">
The problem is with the API server for sure.
Does your API support POST calls? Because as per jtable docs.
If you defined listAction as a URL string, then, when you use the load
method, jTable makes an AJAX POST to this URL address to get list of
records
Also make sure the response JSON response must match the structure.
{
"Result": "OK",
"Records": [
{
"prevExperience": 2,
"employeeName": "Douglas Adams",
"employeeManager": "Simon",
"employeeAddress": "Washigton"
}
]
}
If you want to make a GET call, listAction should be a function instead of a string
actions: {
listAction: function () {
console.log("Loading from custom function...");
return $.Deferred(function ($dfd) {
$.ajax({
url: "https://localhost:44328/api/employee-information/",
type: 'GET',
dataType: 'json',
success: function (data) {
console.log("Success");
$dfd.resolve(data);
},
error: function () {
console.log("Error");
$dfd.reject();
}
});
});
}
}
In your case, the output JSON has structure {result: "OK", records: []}
You need to transform it to {Result: "OK", Records: []} for jtable to work. This can be done in the ajax call success handler like below.
actions: {
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: 'https://localhost:44328/api/employee-information?' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'GET',
dataType: 'json',
success: function (data) {
$dfd.resolve({ Records: data.records, Result: data.result, TotalRecordCount: data.totalRecordCount });
},
error: function () {
$dfd.reject();
}
});
});
}
}
Codepen link with your code.
https://codepen.io/nithinthampi/pen/zYYwgLq
Dummy server with GET.
https://RoundPungentProject.nithinthampi.repl.co

Alpaca title change won't take effect post refresh

I've been trying to slightly modify the observables example found in the docs. Instead of having different enums according to user's choice in the radio button, I want the field below to change the title.
Here's a running fiddle for that.
And the following the code snippet so far:
var teams = {
"None": "None",
"Milwaukee": "Milwaukee",
"Cleveland": "Cleveland",
"Boston": "Boston"
};
$("#form1").alpaca({
"schema": {
"type": "object",
"properties": {
"city": {
"title": "Pick a City",
"type": "string",
"enum": ["Milwaukee", "Cleveland", "Boston"]
},
"team": {
"title": "nothing yet",
"type": "string",
}
}
},
"postRender": function(control) {
var city = control.childrenByPropertyId["city"];
var team = control.childrenByPropertyId["team"];
team.subscribe(city, function(val) {
//city.schema.title = teams[project.data];
console.log('updating field title');
this.schema.title = teams[val];
//this.parent.refresh();
this.refresh();
console.log('refreshed')
});
}
});
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.cloudcms.com/alpaca/1.5.17/bootstrap/alpaca.min.js"></script>
<link href="https://code.cloudcms.com/alpaca/1.5.17/bootstrap/alpaca.min.css" rel="stylesheet"/>
<div id="form1"></div>
In order to change the label of your field you should use options not schema.
this.options.label = teams[val];
Tell me if this isn't working for you.

how to generate form dynamically in angular js?

I am using this https://github.com/Textalk/angular-schema-form plugin to generate my form will not display .I study all documentation and add all js required i didn't get any error but it not display why ?
http://plnkr.co/edit/FO5iEs6ulmP3aR0PW4nt?p=preview
<!DOCTYPE html>
<html >
<head>
<link data-require="bootstrap-css#3.x" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="ui-bootstrap#0.10.0" data-semver="0.10.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="https://dl.dropboxusercontent.com/s/8fq4c4t7jct4w4h/schema-form.js?m="></script>
<script src="https://dl.dropboxusercontent.com/s/unk0id7tmc9w0mm/angular-sanitize.js?m="></script>
<script src="https://dl.dropboxusercontent.com/s/icrciconaesuw29/tv4.js?m="></script>
<script src="https://dl.dropboxusercontent.com/s/rk0dfetihiqs7bi/ObjectPath.js"></script>
</head>
<body>
<div ng-controller="FormController">
<form sf-schema="schema" sf-form="form" sf-model="model"></form>
</div>
<script>
function FormController($scope) {
$scope.schema = {
type: "object",
properties: {
name: { type: "string", minLength: 2, title: "Name", description: "Name or alias" },
title: {
type: "string",
enum: ['dr','jr','sir','mrs','mr','NaN','dj']
}
}
};
$scope.form = [
"*",
{
type: "submit",
title: "Save"
}
];
$scope.model = {};
}
</script>
</body>
</html>
The problem was the javascript plugins included were not in a proper order.
Also use angular.module() to initialize the controller.
JS:
angular.module('test',['schemaForm']).controller('FormController', function($scope,$http){
$scope.schema = {
type: "object",
properties: {
name: { type: "string", minLength: 2, title: "Name", description: "Name or alias" },
title: {
type: "string",
enum: ['dr','jr','sir','mrs','mr','NaN','dj']
}
}
};
$scope.form = [
"*",
{
type: "submit",
title: "Save"
}
];
$scope.model = {};
})
Demo

how to use blur event in form using angular..?

I make a form using this link
I able to validate form on button click, but there is way to validate onBlur but I didn't understand how I will achieve this.
Here is my plunker
<!DOCTYPE html>
<html >
<head>
<link data-require="bootstrap-css#3.x" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body ng-app="test" ng-controller="FormController">
<form name="ngform"
sf-schema="schema"
sf-form="form"
sf-model="model" sf-options="{ formDefaults: { ngModelOptions: { updateOn: 'blur' } }}" ng-submit="onSubmit(ngform)"></form>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//dl.dropboxusercontent.com/s/icrciconaesuw29/tv4.js?m="></script>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="//code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script src="//dl.dropboxusercontent.com/s/unk0id7tmc9w0mm/angular-sanitize.js?m="></script>
<script src="//dl.dropboxusercontent.com/s/rk0dfetihiqs7bi/ObjectPath.js"></script>
<script src="//dl.dropboxusercontent.com/s/8fq4c4t7jct4w4h/schema-form.js?m="></script>
<script type="text/javascript" src="//textalk.github.io/angular-schema-form/dist/bootstrap-decorator.min.js"></script>
<script>
angular.module('test',['schemaForm']).controller('FormController', function($scope,$http){
$scope.schema = {
type: "object",
properties: {
name: { type: "string", minLength: 2, title: "Name", description: "Name or alias" ,required:true},
"email": {
"title": "Email",
"type": "string",
"pattern": "^\\S+#\\S+$",
validationMessage: {
"default": "Just write a proper address, will you?" //Special catch all error message
},
"description": "Email will be used for evil.",
required:true
},
title: {
type: "string",
required:true,
enum: ['dr','jr','sir','mrs','mr','NaN','dj']
}
}
};
$scope.form = [
"*",
{
type: "submit",
title: "Save"
}
];
$scope.model = {};
$scope.onSubmit = function(form) {
// First we broadcast an event so all fields validate themselves
$scope.$broadcast('schemaFormValidate');
// Then we check if the form is valid
if (form.$valid) {
// ... do whatever you need to do with your data.
}
}
})
</script>
</body>
</html>
The ngModelOptions feature has been introduced in angularjs v1.3.0-beta.6
You have to use v1.3.0-beta.6 or newer then your plunker will just work!
Example Plunker: http://plnkr.co/edit/ZCZAcvD2jiBUZhFEcTFA?p=preview

Categories