How to access swagger yaml defined objects from javascript - swagger

I used Swagger Yaml to describe an endpoint and generate the mock server. The existing endpoint (that I'm mocking) doesn't follow RESTful principles 100%, so I simply want to overwrite the response that is returned by the mock server. The simple server code is shown below:
var swagger = require('swagger-server');
var server = swagger('map-cache.yaml');
var port = 7072;
server.post('/map-qa_trunk/v2/getData', function(req, res, next) {
var foo = {
err : 123,
msg : "error message"
};
res.json(foo);
});
server.listen(port, function() {
console.log('Map Cache Mock Server is now running at http://localhost:' + port);
});
In the Yaml definition, there is an object defined called MapResponseData, how do I create an instance of this object so that I can populate it as needed and return in the res.json()? Something similar to below:
var response = getMapResponseData(); // don't know what this call should be
response.fieldA = 123;
res.json(response);
I am guessing this should be possible, since Swagger parsed the YAML file and is aware of all definitions that were specified.

Try outputting the request object to console.log to see if you can find reference to the swagger definition. Another option would be to pull the parsed swagger definition from the yaml file (using js-yaml for example) and extracting from there.
However, my best advice is to use swagger-tools instead of swagger-server. The swagger-server package is alpha version and has fewer downloads, revisions, and users than swagger-tools. Benefit of swagger-tools is that it will be actively maintained and there is a larger community that can support you. To convert your project to swagger-tools, use swagger.io > Swagger Editor > Online Editor > Paste yaml in left pane > Generate Server > Node.js
In swagger-tools the entire Swagger Yaml definition is contained in each request object:
req.swagger.swaggerObject
and you can pull the response object definitions from that as needed.

Related

How to parse attachment values with strongGrid inbound webhook

Hello there I have setup successfully inbound webhook with strongGrid in net core 3.1.
The endpoint gets called and I want to parse value inside the attachment which is csv file.
The code I am using is following
var parser = new WebhookParser();
var inboundEmail = await parser.ParseInboundEmailWebhookAsync(Request.Body).ConfigureAwait(false);
await _emailSender.SendEmailAsyncWithSendGrid("info#mydomain.com", "ParseWebhook1", inboundEmail.Attachments.First().Data.ToString());
Please note I am sending an email as I don t know how to debug webhook with sendgrid as I am not aware of any cli.
but this line apparently is not what I am looking for
inboundEmail.Attachments.First().Data.ToString()
I am getting this on my email
Id = a3e6a543-2aee-4ffe-a36a-a53k95921998, Tag = HttpMultipartParser.MultipartFormDataParser.ParseStreamAsync, Length = 530 bytes
the csv I need to parse has 3 fields Sku productname and quantity I'd like to get sku values.
Any help would be appreciated.
The .Data property contains a Stream and invoking ToString on a stream object does not return its content. The proper way to read the content of a stream in C# is something like this:
var streamReader = new StreamReader(inboundEmail.Attachments.First().Data);
var attachmentContent = await streamReader.ReadToEndAsync().ConfigureAwait(false);
As far as parsing the CSV, there are literally thousands of projects on GitHub and hundreds on NuGet with the keyword 'CSV'. I'm sure one of them will fit your needs.

Change default API spec URL in Swagger UI

I'm using the Swagger Editor Docker image for defining my API specification and generate a nodejs server to run as stub api and serve the documentation for my API spec.
I would like to know if it is possible to change the default URL to my own in order to present my spec when I open the page, and how I would do that.
For instance, I would like to change the default address to http://localhost:8080/spec
If I understand correctly, you used Swagger Codegen to generate a Node.js server. Now when you npm start and open Swagger UI, you want the input box (the spec URL) to display http://localhost:8080/spec instead of http://localhost/api-docs.
To change the path the .yaml spec is served from, edit your index.js as follows:
// 1 - add swaggerUi options
var uiOptions = {
apiDocs: '/spec' // <-- override the default /api-docs
};
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
...
// 2 - pass these options to swaggerUi
app.use(middleware.swaggerUi(uiOptions));
The port number is specified by the serverPort variable in index.js:
var serverPort = 8080;

Swagger UI - reading JSON specs from editor into UI without hosting

I'm attempting to document my API using Swagger by writing the documentation in the Swagger editor and then loading it into the Swagger UI. I used the editor and downloaded my JSON file and then changed the /dist/index.html file within the UI to point to my local file using:
var spec = "file:///Users/user1/Desktop/swagger.json";
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,
spec: spec,
The only thing I changed within the file is the use of the spec var to point to my JSON file, however when I open the UI, it displays a blank UI page with the message "Finished Loading Resource Information. Rendering Swagger UI..." I would just like to display the documentation I created in the editor in the UI without having to host the specs, is there something I'm missing?
Accordign to the Documentation, spec value must be an JSON Object, so you have to do something like:
window.swaggerUi = new SwaggerUi({
spec: JSON.parse('{ "swagger": "2.0", ...')
where
{ "swagger": "2.0", ...
is the content for your file:///Users/user1/Desktop/swagger.json file

best way to tell swaggerui where the host is

When I build my swagger.json file I do not know which host to use. However I can work it out when my page that hosts swaggerui loads (in fact I might want to offer the user a choice). I hoped to see an options.host on the config for the swaggerUI object - I dont see one. Is there an existing way of doing this that I cant find or do I simply have to hack my way through the code and add this capability (pointers to the best place to do it would be welcome)
Swagger has a built-in json definition for host config, or can accept multiple inputs.
{
"swagger": "2.0",
"info": {
"title": "Why API",
"description": "Don't make that mistake again",
"version": "0.0.1"
},
"host": "127.0.0.1:3000",
"schemes": [
"https"
]
}
Or
"host": "test.mydomain.com:3000",
"schemes": [
"https"
],
Or you can have a dynamic host by defining a var and calling a hostname or machine name or other environment variables.
dynamic example
if (typeof this.host === 'undefined' || this.host === '') {
this.host = location.host;
}
if (location.port) {
this.host = this.host + ':' + location.port;
}
Here is what I do, since the loaded in document is just a JSON object:
var swaggerDoc = require('./api/swagger.json');
if (process.env.NODE_ENV === 'development') {
swaggerDoc.host="localhost:" + process.env.PORT
}
// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
// Other initialization
}
This way you don't pollute your API specification with development environment configuration.
In recent versions of Swagger UI it's possible to do this, for example in onComplete:
window.swaggerUi.api.setHost("your.host:4242");
If you are hosting it on same app server, just remove the host key from the json and provide relative path in key "basePath". as -
"basePath": "/rest/createcampaign".
two ways
One modify swagger.js so that it accepts host option. swagger-UI passes options to swagger-js so that works. I submitted a pull to swagger-js with this fix
Second choice is that swagger-UI accepts a 'spec' parameter. This means that the hosting page can load the swagger.json file, JSON.parse it , set 'host' in it and then pass to swaggerUi constructor. This is harder for the caller but doesn't require code changes to swagger
There are 2 ways which you can follow:
Load the index.html and replace the https://petstore.swagger.io/v2/swagger.json with the url where your swagger.json is hosting.
you can expose the local swagger.json on the same server.
When you follow this approach make sure you include static files in the end of above steps.
If you don't want to expose swagger.json as an API, copy the sawgger.json in the dist folder of swagger. The index.html and swagger.json must be in same repository for this. It is inside the index.html of dist folder of swagger-ui-dist.
const ui = SwaggerUIBundle({
spec: location.host,
url: "swagger.json",
dom_id: "#swagger-ui",
deepLinking: true,
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
plugins: [SwaggerUIBundle.plugins.DownloadUrl],
layout: "StandaloneLayout"
});
// End Swagger UI call region
window.ui = ui;
};
Second way, host parameter in the swagger.yaml/swagger.json either make it empty
"host":""
or omit host parameter.
Swagger take the server's host as host where the swagger ui is hosted.
This is how I did this using the Java client:
DefaultApi api = new DefaultApi();
api.getApiClient().setBasePath("http://localhost:8080");
//call the API
if you use OpenApi 3.0
Variables can have arbitrary values, or may be restricted to an enum. In any case, a default value is required, which will be used if the client does not supply a value.
swagger doc
In the swagger-ui there will be the default value but the field is an input field so it is possible to customize it at runtime.
Swagger UI express itself is giving the following snippet it's getting the current host and publish dynamic with host
app.use('/api-docs', function(req, res, next){
swaggerDocument.host = req.get('host');
req.swaggerDoc = swaggerDocument;
next();
}, swaggerUi.serve, swaggerUi.setup());

Swagger UI error: Unable to fetch API Listing

I'm documenting a REST web API with Swagger. I've downloaded the petstore example. It consists of the resources.json which references pet.json and user.json:
{
"apiVersion":"0.2",
"swaggerVersion":"1.0",
"basePath":"http://petstore.swagger.wordnik.com/api",
"apis":
[
{
"path":"/pet.{format}",
"description":"Operations about pets"
},
{
"path":"/user.{format}",
"description":"Operations about user"
}
]
}
But even after uploading the original files to my web server, Swagger UI tells me:
Unable to fetch API Listing. Tried the following urls:
http://www.myserver.org/resources.json
http://www.myserver.org
http://www.myserver.org/resources.json
http://www.myserver.org/resources
Can you tell what causes Swagger not find my json file?
I'm assuming you're going to www.myserver.org and it brings up the swagger ui? In the "Explore" textbox in the Swagger UI... be sure to type in the location of your resources.json.
I personally have my swagger api documentation set up this way...
http://adamclerk.com/api --Swagger UI
http://adamclerk.com/api/doc --returns json representing resources.js
http://adamclerk.com/api/doc/donuts --returns json representing donut operations
you can checkout a more detailed explaination here - Swagger With Static Documentation
If you have any more questions feel free to ask.

Resources