Generate WebAPI documentation in swagger json format - json

I have created a WebAPI using .Net 4.5 and want to document this API using Swagger.
I have added swagger-ui in my .Net project. Now when i browse to ../swagger-ui/index.html it successfully opens pet store api-docs (json) in swagger UI format.
My question is how can I create such (swagger) json for my WebAPI controllers and models? As I have put in required XML summaries/comments to c# classes and attributes.
I saw that Swagger.Net and Swashbuckle are there doing similar things but I could not really understand how to generate swagger-json file using any of them. There might be very small mistake I am doing but unable to point out.
Please help.

As stated, /swagger takes you to the swagger UI.
If you're using Swashbuckle, then /swagger/docs/v1 should take you to the swagger.json file - I found this using Chrome Dev tools.
Edit: if you're using Swashbuckle.AspNetCore, then the url is slightly different - /swagger/v1/swagger.json

You need to integrate Swagger.NET into your project so that you end up with the following controller:
public class SwaggerController : ApiController { /* snip */ }
and you should also have the following route registered:
context.Routes.MapHttpRoute (
name : "Swagger",
routeTemplate: "api/swagger"
defaults: new
{
controller = "Swagger",
action = "Get",
});
assuming that is working you should be able to call /api/swagger and get something like the following:
{
apiVersion: "4.0.0.0",
swaggerVersion: "2.0",
basePath: "http://localhost:5555",
resourcePath: null,
apis: [
{
path: "/api/docs/Values",
description: "No Documentation Found.",
operations: [ ]
},
{
path: "/api/docs/Home",
description: "No Documentation Found.",
operations: [ ]
}
]
}
then in SwaggerUI/index.html you'll want to update the discoveryUrl:
<script type="text/javascript">
$(function () {
window.swaggerUi = new SwaggerUi({
discoveryUrl: "http://localhost:5555/api/swagger",
apiKey:"",
dom_id:"swagger-ui-container",
supportHeaderParams: false,
supportedSubmitMethods: ['get', 'post', 'put']
});
window.swaggerUi.load();
});
</script>

You can use "NSwagStudio" desktop application to load the json document without running the api project.
By providing the api assembly.
https://github.com/RSuter/NSwag/wiki/NSwagStudio
Download the (NSwagStudio) windows desktop application.

Related

NextJs Webpack asset/source returns JSON as a string

Looking for some help to understand what is going on here.
The Problem
We are using a translation service that requires creating JSON resource files of copy, and within these resource files, we need to add some specific keys that the service understands so it knows what should and should not be translated.
To do this as simple as possible I want to import JSON files into my code without them being tree shaken and minified. I just need the plain JSON file included in my bundle as a JSON object.
The Solution - or so I thought
The developers at the translation service have instructed me to create a webpack rule with a type of assets/source to prevent tree shaking and modification.
This almost works but the strange thing is that the JSON gets added to the bundle as a string like so
module.exports = "{\n \"sl_translate\": \"sl_all\",\n \"title\": \"Page Title\",\n \"subtitle\": \"Page Subtitle\"\n}\n";
This of course means that when I try and reference the JSON values in my JSX it fails.
Test Repo
https://github.com/lukehillonline/nextjs-json-demo
NextJs 12
Webpack 5
SSR
Steps To Reproduce
Download the test repo and install packages
Run yarn build and wait for it to complete
Open /.next/server/pages/index.js to see the SSR page
On line 62 you'll find the JSON object as a string
Open .next/static/chunks/pages/index-{HASH}.js to see the Client Side page
If you format the code you'll find the JSON object as a string on line 39
Help!
If anyone can help me understand what is going wrong or how I can improve the webpack rule to return a JSON object rather than a string that would be a massive help.
Cheers!
The Code
next.config.js
module.exports = {
trailingSlash: true,
productionBrowserSourceMaps: true,
webpack: function (config) {
config.module.rules.push({
test: /\.content.json$/,
type: "asset/source",
});
return config;
},
};
Title.content.json
{
"sl_translate": "sl_all",
"title": "Page Title",
"subtitle": "Page Subtitle"
}
Title.jsx
import content from "./Title.content.json";
export function Title() {
return <h1>{content.title}</h1>;
}
pages/index.js
import { Title } from "../components/Title/Title";
function Home({ dummytext }) {
return (
<div>
<Title />
<p>{dummytext}</p>
</div>
);
}
export const getServerSideProps = async () => {
const dummytext = "So we can activate SSR";
return {
props: {
dummytext,
},
};
};
export default Home;

Umbraco 7 route to custom Controller for rest API

i want to map a Route to an ApiController, to post data to it.
I'm not using a Surface contoller, since i want a clean url like /api/test/{action}, without the umbraco/surface part in url.
I'm trying to use
RouteTable.Routes.MapHttpRoute(
"ApiTest",
"Api/Test/{action}",
new
{
controller = "Api_Test",
action = "Search"
});
But i'm getting an error since MapHttpRoute need a 4th string[] parameter.
How can i Map that route?
Then i will post a json or xml and return the response (json or xml).
Use RouteTable.Routes.MapRoute instead. I've used that previously in Umbraco sites and it works fine, e.g.
RouteTable.Routes.MapRoute(
name: "cookie-api-location",
url: "cookie-api/setregioncheckcookie/",
defaults: new
{
controller = "Cookie",
action = "SetRegionCheckCookie"
}
);

Generating JSON object of the tests ran using Protractor?

I'm relatively new to end to end testing with Protractor, Mocha and Yadda (for integration with Mocha so I can use Gherkin and step definitions).
I've seen a plugin called Mochawesome which generates an HTML report which can be viewed offline, along with this JSON object of the test results, all of which contained in a 'reports' folder.
I presume it's Mochawesome which generates these JSON objects as the HTML page seems to have corresponding tags etc. Is there any way to generate a JSON object of the tests ran without the HTML reporter? The idea was to create my own sort of 'dashboard' containing information about the tests based on the JSON information.
Yes you can create a JSON report of your specs/tests with protractor.You just have to put resultJsonOutputFile: './Report.json' in your config file.
your config file should somewhat look like this:
exports.config = {
directConnect: true,
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://juliemr.github.io/protractor-demo/',
framework: 'jasmine2',
specs: ['*spec.js '],
allScriptsTimeout: 180000,
getPageTimeout: 180000,
jasmineNodeOpts: {
defaultTimeoutInterval: 180000
},
resultJsonOutputFile: './Report.json', // It would create report.json file in your current folder
onPrepare: function () {
browser.driver.manage().window().maximize();
browser.ignoreSynchronization = true;
}
};
You can consume this json report and use it in your way!
I'm not sure about generating JSON object directly in protractor. But what i know is that, we can generate results in XML and then convert xml to json by writing some customized code.
Code for generating XML reports are as follows:
framework: "jasmine2",
onPrepare: function() {
var jasmineReporters = require('jasmine-reporters'),
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
savePath: '../result/',
filePrefix: ‘report’,
consolidateAll: true
});
);
},

Angular resource 404 Not Found

I've read other posts that have similar 404 errors, my problem is that I can correctly query the JSON data, but can't save without getting this error.
I'm using Angular's $resource to interact with a JSON endpoint. I have the resource object returning from a factory as follows:
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' });
});
My JSON is valid and I can successfully use resource's query() method to return the objects inside of my directive, like this:
var item = Product.query().$promise.then(function(promise) {
console.log(promise) // successfully returns JSON objects
});
However, when I try to save an item that I've updated, using the save() method, I get a 404 Not Found error.
This is the error that I get:
http://localhost:3000/api/products.json/12-34 404 (Not Found)
I know that my file path is correct, because I can return the items to update the view. Why am I getting this error and how can I save an item?
Here is my data structure:
[
{
"id": "12-34",
"name": "Greece",
"path": "/images/athens.png",
"description": ""
},
...
]
By default the $save method use the POST verb, you will need to figure out which HTTP verbs are accepted by your server en order to make an update, most modern api servers accept PATCH or PUT requests for updating data rather than POST.
Then configure your $resource instance to use the proper verb like this :
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' }, {'update': { method:'PUT' }});
});
check $resource docs for more info.
NOTE: $resource is meant to connect a frontend with a backend server supporting RESTful protocol, unless you are using one to receive data & save it into a file rather than a db.
Otherwise if you are only working with frontend solution where you need to implement $resource and have no server for the moment, then use a fake one, there is many great solutions out there like deployd.
You probably don't implement POST method for urls like /api/products.json/12-34. POST method is requested from angular for saving a new resource. So you need to update your server side application to support it and do the actual saving.
app.factory('Product', function($resource) {
return $resource('api/products.json/:id', { id: '#id' });
});
Try adding "/:id" at the end of the URL string.

Collection+JSON with AngularJS

I'm working on a project where various tables of data will be displayed with AngularJS. The data will be in the Collection+JSON format, as shown below. I found this library https://github.com/Medycation/angular-collection-json, I'm not sure how to make it work. Below is an example of the data.
angular.module('app', ['cj']);
var $injector = angular.injector();
var cj = $injector.get('cj');
cj("cjapi1.php").then(function(cjProvider){
console.log(collection.items());
});
I tried the above. In the console it says I need to register cjProvider as a provider. Any help with how to set this up properly would be appreciated. Thanks.
{
“collection”:
{
“version”: “0.1”,
“href” : “https://example.com/companies”
“items” : [
{
“href” : “https://example.com/companies/123”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 1”}
}
},
{
“href” : “https://example.com/companies/1234”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 2”}
}
},
]
}
Please configure your cjProvider while configuring your module. Check the below code template for the reference to configure cjProvider.
angular.module('app', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});
Please make sure that you have configured your transformUrl just shown above.
Your base url must be configured in cjProvider and while hitting any url ang getting data you should transform your request like here you are requesting cjapi1.php. so your baseurl must be append before that like your_base_url + 'cjapi1.php' this will be done for all requesting api. So cjProvider will take care that and will return api path and in .then(responce) you will get your responce which is collection.
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
Are you trying to configure or get the contents of the collection from php call?
Looks like a typo to me but try this to get collection:
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
...and this for configuration of your provider:
angular.module('agile', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});