How to get Swagger API JS function names? - javascript

I'm new to Wordnik and Swagger in general. I'm interacting with it through the Node.js JS module.
When looking at the generated Swagger UI pages, such as the sample Petstore Swagger one:
it is difficult to tell what the JavaScript functions should be when querying the server.
By JavaScript functions, I mean similar to the Petstore sample example (from the swagger-js docs):
var Swagger = require('swagger-client');
var client = new Swagger({
url: 'http://petstore.swagger.io/v2/swagger.json',
success: function() {
client.pet.getPetById({petId:7},{responseContentType: 'application/json'},function(pet){
console.log('pet', pet);
});
}
});
After connecting to swagger.json, how do they know the function to query the getPetById() function when the docs only show GET /pet/{petId}?
When using the Wordnik API, I've found it a general rule of thumb to use the get{DATATYPE}() function (with {DATATYPE} replaced with an appropriate value, of course), but the pattern has broken with getPronunciation() — it doesn't work. I don't believe the docs say it anywhere.
How could I find the JS functions for Swagger APIs?

The JavaScript method name is the same as the nickname and/or operationId field of each operation in the Swagger document, depending on which one is available.
This is an example from the Wordnik:
"path": "/word.{format}/{word}/pronunciations",
"description": "",
"operations": [
{
...
"nickname": "getTextPronunciations",
"responseClass": "List[TextPron]"
}
]
},
In this example getTextPronunciations is the JS method name.
In Wordnik, you can get the swagger.json by clicking on the Raw button on the word section of the document (next to the Expand Operations button). You can find all the other swagger.json files here: http://developer.wordnik.com/v4/

Related

Alfresco get the path of documents using CMIS

I'm trying to fetch document objects from Alfresco Community edition,I need the documents path, while i use
SELECT * FROM cmis:document where ''
but i thing the cmis:document namespace doesn't return the path, i was wondering if there is a way to include the path.
PS : i can only use JAVASCRIPT with cmis queries
Instead of a CMIS query you should just fetch the object by URL using its object ID, then grab the path. The browser binding, which is easily invocable from JavaScript, supports this.
For example, suppose I have a file named "test-1.txt" sitting in a folder called "/test" with an Alfresco object ID of:
workspace://SpacesStore/1fb2d9cf-11ca-47c2-94b4-cf72de8f9b92
I can use this URL:
http://localhost:8080/alfresco/api/-default-/public/cmis/versions/1.1/browser/root?objectId=workspace://SpacesStore/1fb2d9cf-11ca-47c2-94b4-cf72de8f9b92&cmisselector=parents&includerelativepathsegment=true
To return JSON that includes:
{
"id": "cmis:path",
"localName": "path",
"displayName": "Path",
"queryName": "cmis:path",
"type": "string",
"cardinality": "single",
"value": "\/test"
}
Which contains the path.
You can shorten up the JSON significantly by also adding "&succinct=true"
Another option would be to write your own Javascript backed web script. It's controller would find the node using CMIS query, and it's FTL would actually display the path in any format you like.
https://community.alfresco.com/docs/DOC-6243-50-javascript-api
http://docs.alfresco.com/5.0/references/API-JS-ScriptNode.html

Swagger UI with digest authentication

I'm using Swagger to produce the documentation of my REST API. According to what is written around, the Swagger UI does not offer support for basic authentication (differently from the online editor). My problem is that one of my APIs is a POST that require digest (not even basic) authentication.
A possible solution I found around is to add a fixed user:pass authentication header in the request via javascript code. This should be easily done according to the Swagger UI documentation (see Custom Header Parameters). I report the incriminated code line:
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "XXXX", "header"));
Unfortunately it doesn't work. The swaggerUi.api field results uninitialised (null) after I initialise the SwaggerUi object, and as a consequence swaggerUi.api.clientAuthorizationsis undefined. I tried initialising such fields in different way, failing every time. I tried also similar calls to the API I found in threads discussing this topic, but none of them has worked. Does anyone have an idea about that? The documentation is not particularly clear about that.
For completeness, I report the js snippet where I initialise the Swagger UI
var urlPush = "./doc_push.yaml";
window.swaggerUiPush = new SwaggerUi({
url: urlPush,
dom_id: "swagger-ui-container-push",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "list",
jsonEditor: false,
defaultModelRendering: 'model',
showRequestHeaders: false,
});
Try using SwaggerClient.PasswordAuthorization instead of SwaggerClient.ApiKeyAuthorization -
var username = $('#input_username').val();
var password = $('#input_password').val();
var basicAuth = new SwaggerClient.PasswordAuthorization('basic', username, password);
window.swaggerUi.api.clientAuthorizations.add("basicAuth", basicAuth);

With VersionOne api, how to implement fetch of Story Names when implemented by javascript / html? query.v1 using Oauth2

I would like to begin consuming VersionOne api to use as building block for presenting custom HTML page view of Story Names (expand details on this later once I got the initial thing working). I'd like to formulate this in HTML, javascript, JSON, OAUTH2 (no callback URL) implementation. For this implementation the query.v1 endpoint is required and the usage/setup instructions for me aren't as clear/easy to use as the rest-1.v1.
I did "build"/download my personal client secret("v1_client_secrets.json). Although I do not know what "using the scope query-api-1.0" from the documentation means or how it would get applied. Api documentation I have been reading is here: https://community.versionone.com/Developers/Developer-Library/Sample_Code/Tour_of_query.v1
I am fine with the json data GET pattern below.
{
"from": "Story",
"select": [
"Name"
]
}
Although there are examples of the JSON patterns, I can't seem to understand how to code it from start to finish. Is there a starter template script (includes all html/javascript) based on my details, that someone could pass along? I am assuming jquery, angular, ajax would be incorporated in the retrieval/parse/read process.
FYI, I am new to this coding, especially consuming api, so hoping this all makes sense.
Using the Javascript SDK you can communicate with a VersionOne instance. If you are using node you can install the package with npm install v1sdk. Otherwise the source code can be downloaded at https://github.com/versionone/VersionOne.SDK.JavaScript/ . An example of this.
import $ from 'jquery';
import sdk, {jqueryConnector} from 'v1sdk';
const jqueryConnectedSdk = jqueryConnector($)(sdk);
const v1 = jqueryConnectedSdk('www14.v1host.com', 'v1sdktesting', 443, true)
.withCreds('admin', 'admin'); // usage with username/password
// .withAccessToken('your token'); // usage with access tokens
v1.create('Story', {estimate: 5, status: 'Not Started'})
.then((story) => v1.update(story.oidToken, {estimate: 7}))
.then(v1.query({
from: 'Story',
select: ['Estimate', 'Status'],
where: {
Status: 'Not Started'
}
}))
.then(console.log)
.catch(console.log);
This example shows creating a v1 connection, creating a story, updating that story, and then querying for that same story and selecting the Estimate and Status where the Status is 'Not Started'. This is an article that gives an example of displaying the backlog using the SDK http://walkerrandolphsmith.com/blog/v1sdk/. It also has an accompanying git repo you can look at mentioned in the article.

Using meteor and blaze how to convert template to string for an email body?

And how can I set the value of this now? Ie in js? All i see is how to do in handlebars.
From Meteorpedia :
http://www.meteorpedia.com/read/Blaze_Notes
Take a look at "How to render a template to HTML with data"
var toHTMLWithData = function (kind, data) {
return UI.toHTML(kind.extend({data: function () { return data; }}));
};
Use it like this :
var myTemplateAsString=toHTMLWithData(Template.myTemplate,dataContext);
Which is equivalent to previous Spark code :
var myTemplateAsString=Template.myTemplate(dataContext);
Currently Meteor does not natively support server side rendering of templates, and since you are sending emails from the server this creates an issue. Server side rendering is on the Meteor roadmap, but for now we can use a package. its called "Handlebars-server" and it can be found here: https://atmospherejs.com/package/handlebars-server
With Handlebars-server you can compile handlebars templates into strings for use in emails. The package's readme should get you started and show you how to set data context.

How should I handle Asp.net MVC URLs in javascript calls?

I am attempting to write a javascript heavy portion of my Asp.net MVC Web App (this portion of the website is a RIA using Extjs). However, I have come up to a standstill at the correct way to handle URLs in the javascript.
For example, right now I have an Ajax call to the List action in the ObjectsController, which resides in the Reading area. The List action takes a parameter of documentId (int). As of right now, this maps to /Reading/Objects/List since I have no changed routing yet (the site is too young at the moment to finalize routes). Normally in a view, to put this URL in a string I would do #Html.Action("List", "Objects", new { area = "Reading", documentId = 3).
However, this doesn't work when dealing with javascript, since javascript isn't parsed by a viewengine.
To get around this, I have a very small view that returns javascript constants, such as URLs, that is loaded prior to my main application's js files. The issue is that I can't call Html.Action for this action because at constant creation time I (obviously) do not know what documentId the ajax calls are going to be, and if you exclude documentId from the Html.Action call an exception occurs. The documentId could change during the normal workflow of the application.
How do I handle this? I don't want to hardcode the URL to /Reading/Objects/List because if I change my routing for this (for a more user friendly json API), or this web app isn't hosted on the root of the domain, the URL will no longer be valid.
How does everyone else handle MVC URLs in their javascript calls?
Here's a safe technique that I've been using. Even if your route changes, your JavaScript will automatically conform to the new route:
<script>
var url = '#Url.Action("List", "Objects", new { area = "Reading", documentId = "_documentId_")';
var id = 100;
var finalUrl = url.replace('_documentId_', id);
</script>
"_documentId_" is essentially a dummy placeholder. Then inside my JavaScript, I replace "_documentId_" with the proper id value once I know what it is. This way, regardless of how your route is configured, your URL will conform.
Update: Dec 20
I just saw this interesting blog post. The author built a library that allows you to build routes inside of your JavaScript file with intellisense support in VisualStudio.
http://weblogs.asp.net/zowens/archive/2010/12/20/asp-net-mvc-javascript-routing.aspx
Personally I use unobtrusive javascript and avoid mixing markup with javascript. AJAX calls are normally triggered by clicking on some buttons or links:
#Html.ActionLink("click me", "List", "Objects",
new { area = "Reading", documentId = 3 }, new { id = "foo" })
and then in a separate js file I would attach and handle the onclick event (example with jquery):
$(function() {
$('#foo').click(function() {
$('#resultDiv').load(this.href);
return false;
});
});
As you can I didn't need to use any hardcoded URL in my javascript file. URLs should always be handled by the routing engine and generated with html helpers.
If it was a <form> instead of a link I would simply handle the onsubmit event (the same way) and use the form's action attribute to get the URL.
UPDATE:
After pointing out in the comments section that the documentId is known only at client-side you could do this:
#Html.ActionLink("click me", "List", "Objects",
new { area = "Reading" }, new { id = "foo" })
And then:
$(function() {
$('#foo').click(function() {
$('#resultDiv').load(this.href, { documentId: '123' });
return false;
});
});
Turns out, this was all solved by using Url.Action() instead of Html.Action(). Url.Action() is (so far) allowing me to generate URLS without all of the parameters. I am assuming that this only works when the route does not specify the parameters in the target URL itself.

Categories

Resources