Swagger UI disable Try It Out button - swagger-ui

I would like to disable Try it Out button in the API documentation. I have tried "tryItOut": false in the parameter and the configuration. Furthermore, I'm using swagger 2.0 which has 'Try it out' button is enabled by default and in 3.0 it is disabled by default. So, there should be option to configure it. How to disable Try it out button from the Swagger UI?

Set supportedSubmitMethods to an empty array [] in your Swagger UI configuration. This config option is supported in v. 3.10.0+.
const ui = SwaggerUIBundle({
"dom_id": "#swagger-ui",
url: "https://path/to/your/api.yaml",
...
supportedSubmitMethods: [] // <--------
})
This config can also disable "Try it out" selectively for specific HTTP methods. For example, supportedSubmitMethods: ["get", "head"] keeps "Try it out" only for GET and HEAD, but disables it for POST, PUT, PATCH, DELETE and other methods.

From the GitHub repository comments, the bellow code works to me
const DisableTryItOutPlugin = function() {
return {
statePlugins: {
spec: {
wrapSelectors: {
allowTryItOutFor: () => () => false
}
}
}
}
}
// elsewhere, when you call Swagger-UI...
SwaggerUI({
plugins: [
DisableTryItOutPlugin
]
})
Reference: https://github.com/swagger-api/swagger-ui/issues/3725#issuecomment-334899276

In Swagger UI Options, try this for .NET 6 or 7:
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Nrp API");
options.EnableTryItOutByDefault();
});

Related

In electron how to send custom header and value for every request?

I use electronjs for building a cross platform desktop application. I would like to send a custom header with a value for every request from electron. Initially in loadURL(), i could use extraHeaders to set the custom header. How to send it in all subsequent requests?
As recommended by the documentation, you should use session object and the method onBeforeSendHeaders:
const { session } = require('electron')
// Modify the user agent for all requests to the following urls.
const filter = {
urls: ['https://*.github.com/*', '*://electron.github.io']
}
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
details.requestHeaders['User-Agent'] = 'MyAgent'
callback({ requestHeaders: details.requestHeaders })
})

Custom docs for feathers.js services with Swagger

I have configured Swagger within my Feather.js app and it automatically generates docs for all endpoints on each service. Now, some endpoints on some service I want to omit from being generated as docs, because I simply disallow these endpoints or have some hidden logic behind them, that does not allow external calls.
F.e. I have the following setup for the endpoints of my /users/me service:
before: {
all: [authenticate('jwt')],
find: [
/*
* We don't use an ID when calling `/users/me` like `/users/me/<id>`, and therefore Feathers understands the
* incoming request as a `find` method instead of `get`, therefore we simply redirect it internally.
*/
async context => {
context.result = await context.service.get(context.params.user.id); // eslint-disable-line
return context;
}
],
get: [
iff(isProvider('external'), disallow()),
includeGender()
],
create: [disallow()],
update: [setAuthenticatedUserId()],
patch: [setAuthenticatedUserId()],
remove: [setAuthenticatedUserId()]
}
As you can see from the logic setup, I want to have the following docs generated:
I've followed these docs regarding feathers-swagger. I use the schemasGenerator(service, model, modelName, schemas) to generate docs for each service. Understandably this will generate the same schema of docs for each service. I tried adding custom stuff, as per the github module explanations, by either adding the docs object:
service.docs = {
...service.docs,
operations: {
find: false,
create: false
}
};
or adding a global operations: { find: false, create: false } object on the Swagger config.
The first option doesn't have an effect, and the second option applies it to all endpoints, which doesn't help me.
You must use the 'ignore' option to exclude the end-points that you want to. You may either specify the 'tags' array or the 'paths' array.
app.configure(swagger({
docsPath: '/api/docs',
uiIndex: true,
specs: {
info: {
title: 'API Docs',
description: 'Rest APIs',
version: '1.0.0',
},
schemes: ['http', 'https'],
},
ignore: {
paths: [
'users'
]
}
}));
You can also ignore end-points from service level.
usersService.docs = {
description: 'A service to manage users',
definitions: {
users: m2s(options.Model),
'users_list': {
type: 'array',
items: { $ref: '#/definitions/users' }
}
},
securities: ['find', 'get', 'update', 'patch', 'remove'],
operations: {'create': false}
};
Get complete documentation for feathers-swagger here

Display only endpoints available to user in Swagger after his login

I would like to setup the follownig workflow:
Initially, without login, Swagger shows only 2-3 endpoints - this will be done by providing limited openapi3 json from backend, no problem;
User logs in via Authorize button (works, openapi3 json has necessary info);
After login, Swagger emits one more request with user credentials, backend provides new openapi3 json with endpoints available to this specific user and Swagger redraws the page with new data. Preferably, user is still logged in.
Is it possible to do Item 3 with Swagger? How can I manually emit request from Swagger with OAuth2 bearer token (since user logged, token must present somwhere) and redraw Swagger page?
The task was done via Swagger customization using its plugin system.
Actually Swagger is a JavaScript (Babel, Webpack) project using React / Redux and it was a little bit hard to dig into it since I do not know React (my tool is Python) but finally I managed.
Here is the code for my custom plugin with comments:
const AuthorizedPlugin = function(system) {
return {
statePlugins: {
auth: { // namespace for authentication subsystem
// last components invoked after authorization or logout are
// so-called reducers, exactly they are responsible for page redraw
reducers: {
"authorize_oauth2": function(state, action) {
let { auth, token } = action.payload
let parsedAuth
auth.token = Object.assign({}, token)
parsedAuth = system.Im.fromJS(auth)
var req = {
credentials: 'same-origin',
headers: {
accept: "application/json",
Authorization: "Bearer " + auth.token.access_token
},
method: 'GET',
url: system.specSelectors.url()
}
// this is the additional request with token I mentioned in the question
system.fn.fetch(req).then(
function (result) {
// ... and we just call updateSpec with new openapi json
system.specActions.updateSpec(result.text)
}
)
// This line is from the original Swagger-ui code
return state.setIn( [ "authorized", parsedAuth.get("name") ], parsedAuth )
},
"logout": function(state, action) {
var req = {
credentials: 'same-origin',
headers: { accept: "application/json" },
method: 'GET',
url: system.specSelectors.url()
}
// for logout, request does not contain authorization token
system.fn.fetch(req).then(
function (result) {
system.specActions.updateSpec(result.text)
}
)
// these lines are to make lock symbols gray and remove credentials
var result = state.get("authorized").withMutations(function (authorized) {
action.payload.forEach(function (auth) {
authorized.delete(auth);
});
});
return state.set("authorized", result)
}
}
}
}
}
}
Insert this plugin as usual:
const ui = SwaggerUIBundle({{
url: '{openapi_url}',
dom_id: '#swagger-ui',
defaultModelsExpandDepth: -1,
displayOperationId: false,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
plugins: [
AuthorizedPlugin
],
layout: "BaseLayout",
deepLinking: true
})

Migrate Google Workbox setDefaultHandler // setCatchHandler from v2 to v3

I'm trying to migrate my old code from google workbox v2 to workbox v3, and i can't use workbox.routing.registerNavigationRoute because my default route '/' (which is where my appshell is) is a runtime cache (because it's for a multilingual website https://www.autovisual.com with languages put in subfolder '/fr', '/es' ... with a unique Service-Worker scoped at '/').
This is the v2 code :
workboxSW.router.setDefaultHandler({
handler: ({
event
}) => {
return fetch(event.request);
}
});
workboxSW.router.setCatchHandler({
handler: ({
event
}) => {
if (event.request.mode === 'navigate') {
return caches.match('/');
}
return new Response();
}
});
It seems pretty basic : the goal is to catch all request 'navigate' that didn't match any other route and send the cached version, network first, of the url '/'.
For the info in the client js i use :
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
caches.open('rootCacheNetworkFirst').then(function(cache) {
cache.match('/').then(function(response) {
if (!response) {
cache.add('/');
}
});
});
navigator.serviceWorker.register('/sw.js', {
scope: "/"
});
});
}
I can't find any example with the new v3 workbox.routing.setDefaultHandler and workbox.routing.setCatchHandler and i'm stuck :(
I don't think that using either setDefaultHandler or setCatchHandler is relevant for that described use case.
To accomplish what you describe, add the following code to your service worker file after all other routes are registered. (In Workbox v3, the first-registered-route takes precedence.) You just need to configure a NavigationRoute and register it:
const networkFirst = workbox.strategies.networkFirst({
cacheName: 'your-cache-name',
});
const navigationRoute = new workbox.routing.NavigationRoute(networkFirst, {
// Set blacklist/whitelist if you need more control
// over which navigations are picked up.
blacklist: [],
whitelist: [],
});
workbox.router.registerRoute(navigationRoute);

How to remove the API definition URL under title in Swagger UI?

I'm using Swagger UI and want to remove the API definition URL (link to the YAML file) displayed under the title section as highlighted on the picture. Can this be done by customizing the Swagger UI index.html page?
Option 1: Hide using CSS
<!-- index.html -->
<style>
...
.swagger-ui .info hgroup.main a {
display: none
}
</style>
Option 2: Hide using JavaScript (v.3.13.0+)
Swagger UI 3.x uses the plugin system to control the rendering. You can define a custom plugin that disables the InfoUrl component - this will prevent the API definition link from being rendered. This approach works in Swagger UI 3.13.0 and later.
// index.html
window.onload = function() {
// Custom plugin to hide the API definition URL
const HideInfoUrlPartsPlugin = () => {
return {
wrapComponents: {
InfoUrl: () => () => null
}
}
}
// Build a system
const ui = SwaggerUIBundle({
...
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
HideInfoUrlPartsPlugin // <---- Apply the plugin
],
...
})
Source

Resources