Swagger ui url with parameters - html

How to pass base url in the form http://localhost:3000/resources/api/?key=aslkdajd1323121lklakskdl to swagger ui ?
I was able to access http://localhost:3000/resources/api but when I add auth filter and pass key, it says, Unauthorized.
Using swagger 1.X
Pre-populating the parameter through apiKeyauthorization in index.html did not help, but when I type in the key in UI, it worked. Unable to understand the reason for this. Hope someone can help me make sense out of it.

Try this swagger 2.0 file (use http://studio.restlet.com to downgrade to version 1.2) :
{
"swagger": "2.0",
"info": {
"version": "0.0.1",
"title": "Todo App"
},
"host": "localhost:3000",
"schemes": [
"http"
],
"paths": {
"/resources/api": {
"post": {
"parameters": [
{
"name": "key",
"in": "query",
"description": "key",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "Successful response"
}
}
}
}
}
}

I was able to solve this by adding
window.authorizations.add("key", new ApiKeyAuthorization("key", yourKeyValue, "query"));
in the SwaggerUI constructor function
window.swaggerUi = new SwaggerUi({ . . .
right before the statement
window.swaggerUi.load()

You just need get the parameter from the url with javscript. In the file "index.html", under swagger-ui/dist folder, add something like this to get your key:
var key = window.location.search.match(/key=([^&]+)/);
You can see a simple example in my GIST.

Related

Invalid OpenAPI JSON file - Expected type object but found type string for security definition

I'm getting a validation error for the following openApi.json file, which I'm trying to configure in order to use JWT authentication to my Endpoints service on Google Cloud. I'm following this guide - https://cloud.google.com/endpoints/docs/openapi/service-account-authentication#configure_auth. The error can be easily reproduced by pasting and validating my sample using the Swagger online parser. The error message is:
Swagger schema validation failed.
Expected type object but found type string at #/paths//my/api/get/responses/200/description/securityDefinitions/mySecurityDefinition/x-google-jwks_uri/x-google-issuer/type/flow/authorizationUrl/security/0
JSON_OBJECT_VALIDATION_FAILED
I'd like to understand why I get the message Expected type object but found type string. The error message looks like it's maybe complaining about the security definition, but I'm not seeing why.
openapi.json
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "my-app-hostname.appspot.com"
},
"host": "my-app-hostname.appspot.com",
"basePath": "/api",
"schemes": [
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"security" : [
"mySecurityDefinition"
],
"securityDefinitions": {
"mySecurityDefinition": {
"authorizationUrl": "",
"flow": "implicit",
"type": "oauth2",
"x-google-issuer": "myServiceAccountEmailAddress",
"x-google-jwks_uri": "https://www.googleapis.com/robot/v1/metadata/x509/myServiceAccountEmailAddress"
}
},
"paths": {
"/my/api": {
"get": {
"responses": {
"200": {
"description": "A successful response"
}
}
}
}
}
}
What am I doing wrong? If I change the 1st object in the security array to this, then it doesn't validate, but the parser gives no error message:
"security" : [
{
"mySecurityDefinition": [ ]
}
],

How to create new alerts in azure for all webapps at same time

I want to create new alerts(High CPU,RAM) for all AppServicePlans in a given subscription. I could not find Powershell commands to create new alerts. Is there a way we can create these alerts for all appserviceplans with a single script? May be using ARM template?
Sorry for pasting a direct answer, but I cannot yet comment. You get the error because in the documentation for Add-AzMetricAlertruleV2 it states: "$act is the output of New-AzActionGroup cmdlet". Meaning you need to use for example:
$act = New-AzActionGroup -ActionGroupId "testActionGroup"
After that you need to add it in the parameter -ActionGroup $act for it to work.
If you look at Resource Explorer and navigate to a manually created (near-realtime) alert, you should see the "critera" object defined like below. Here is a full example of a resource that seems to be working. Create some variables for each of your values:
{
"type": "Microsoft.Insights/metricAlerts",
"apiVersion": "2018-03-01",
"name": "[variables('alertName')]",
"location": "global",
"dependsOn": [],
"tags": {
"[concat('hidden-link:', variables('applicationInsightsResourceId'))]": "Resource",
"[concat('hidden-link:', variables('webtestResourceId'))]": "Resource"
},
"properties": {
"description": "[concat('Alert for ', parameters('availibilityTestName'))]",
"severity": 4,
"enabled": true,
"scopes": [
"[variables('webtestResourceId')]",
"[variables('applicationInsightsResourceId')]"
],
"evaluationFrequency": "PT5M",
"windowSize": "PT15M",
"criteria": {
"odata.type": "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria",
"webTestId": "[variables('webtestResourceId')]",
"componentId": "[variables('applicationInsightsResourceId')]",
"failedLocationCount": 3
},
"actions": [
{
"actionGroupId": "[resourceId('microsoft.insights/actiongroups', 'webhook')]",
"webHookProperties": {
// Some properties to send to webhook
}
}
]
}
}

Defining Azure Stream Analytics iot-hub input source through Powershell

I'm trying to write a powershell script that creates a new streamAnalytics job in my azure portal account, with input source as iot-hub and output source as blob storage account.
To do so, I'm using AzureRM command new-streamAnalyticsJob, and json files.
my problem is: I have not seen any documentation or example for json file where the inputs source is iot-hub. only event-hub.
what are the parameters I need to give in the json file? can anyone display an example for json file with input source to streamAnalytics job as Iot-hub?
I got the answer eventually: the required field I had to add to the inputs Oliver posted earlier here is:
"endpoint":"messages/events"
I added it under Datasource Properties section, and it works fine!
Thanks Oliver
To come back on the error message you are seeing, to add to Olivier's sample you need a Property named endpoint which corresponds to the endpoint in IoT Hub. If you are looking for Telemetry messages this will be:
"endpoint": "messages/events"
This can be found in the schema for Azure ARM: https://github.com/Azure/azure-rest-api-specs/blob/current/specification/streamanalytics/resource-manager/Microsoft.StreamAnalytics/2016-03-01/examples/Input_Create_Stream_IoTHub_Avro.json
So to complete Olivier's example, when using API version '':
"Inputs": [
{
"Name": "Hub",
"Properties": {
"DataSource": {
"Properties": {
"consumerGroupName": "[variables('asaConsumerGroup')]",
"iotHubNamespace": "[parameters('iotHubName')]",
"sharedAccessPolicyKey": "[listkeys(variables('iotHubKeyResource'), variables('iotHubVersion')).primaryKey]",
"sharedAccessPolicyName": "[variables('iotHubKeyName')]",
"endpoint": "messages/events"
},
"Type": "Microsoft.Devices/IotHubs"
},
"Serialization": {
"Properties": {
"Encoding": "UTF8"
},
"Type": "Json"
},
"Type": "Stream"
}
}
],
That'd look like the following for the inputs part of the ASA resource:
"Inputs": [
{
"Name": "IoTHubStream",
"Properties": {
"DataSource": {
"Properties": {
"consumerGroupName": "[variables('CGName')]",
"iotHubNamespace": "[variables('iotHubName')]",
"sharedAccessPolicyKey": "[listkeys(variables('iotHubKeyResource'), variables('iotHubVersion')).primaryKey]",
"sharedAccessPolicyName": "[variables('iotHubKeyName')]"
},
"Type": "Microsoft.Devices/IotHubs"
},
"Serialization": {
"Properties": {
"Encoding": "UTF8"
},
"Type": "Json"
},
"Type": "Stream"
}
}
]

Orion Context Broker - subscriptions

I have a small problem. Im doing a subscription to Orion Context Broker and I have a strange problem with URL of callback:
this code works from tutorial:
{
"entities": [
{
"type": "Room",
"isPattern": "false",
"id": "Room1"
}
],
"attributes": [
"temperature"
],
"reference": "http://localhost:1028/accumulate",
"duration": "P1M",
"notifyConditions": [
{
"type": "ONTIMEINTERVAL",
"condValues": [
"PT10S"
]
}
]
}
But this code doesnt work:
{
"entities": [
{
"type": "Room",
"isPattern": "false",
"id": "Room1"
}
],
"attributes": [
"temperature"
],
"reference": "http://192.168.1.12:1028/accumulate?name=dupex",
"duration": "P1M",
"notifyConditions": [
{
"type": "ONTIMEINTERVAL",
"condValues": [
"PT10S"
]
}
]
}
Only difference is reference field:
"reference": "192.168.1.12:1028/accumulate?name=dupex"
I got:
{
"subscribeError": {
"errorCode": {
"code": "400",
"reasonPhrase": "Bad Request",
"details": "Illegal value for JSON field"
}
}
}
Any Suggestion please :) thank you.
The root cause of the problem is that = is a forbidden character, not allowed in payload request for security reasons (see this section in the user manual about it).
There are two possible workarounds:
Avoid the usage of query strings in the URL for reference in subscribeContext, e.g. using http://192.168.1.12:1028/accumulate/name/dupex.
Encode URL encoding to avoid forbidden characters (in particular, the code for = is %3D) and prepare your code to decode it.
In case 2, you could use the follwoing reference in subscribeContext: http://192.168.1.12:1028/accumulate?name%3Ddupex. Then, an example of code that will take into account the encoding and get the name argument properly would be the following (written in Python using Flask as REST server framework):
from flask import Flask, request
from urllib import unquote
from urlparse import urlparse, parse_qs
app = Flask(__name__)
#app.route("/accumulate")
def test():
s = unquote(request.full_path) # /accumulate?name%3Dduplex -> /accumulate?name=duplex
p = urlparse(s) # extract the query part: '?name=duplex'
d = parse_qs(p.query) # stores the query part in a Python dictionary for easy access
name= d['name'][0] # name <- 'duplex'
# Do whatever you need with the name...
return ""
if __name__ == "__main__":
app.run()
I guess that a similar approach can be used in other languages (Java, Node, etc.).
EDIT: Orion version 1.2 support notification customization in the NGSIv2, which allows this use case. For example, you can define the following subscriptions:
{
..
"notification": {
"httpCustom": {
"url": "http://192.168.1.12:1028/accumulate",
"qs": {
"name": "dupex"
}
}
..
}
..
}
Please have a look to "Subscriptions" and "Custom Notifications" sections at NGSIv2 Specification for details.

Asana- Invalid Field

I'm POST'ing the following JSON to asana's "tasks" endpoint.
{
"data": {
"options": {
"fields": [
"name",
"notes"
]
},
"workspace": <valid number>,
"assignee": <valid number>
}
}
It's giving me a "Invalid field" error every time. I've read through the API a few times now and this JOSN looks exactly how the API says it should. Any ideas?
Asana API for those of you who want to help out: Asana API Documentation
(I work for Asana)
The "options" field is a sibling of the "data" field, not a child. This is mentioned in the docs, but perhaps we aren't providing clarifying examples to make it more obvious.
If you change your request to look like this:
{
"options": {
"fields": [
"name",
"notes"
]
},
"data": {
"workspace": <valid number>,
"assignee": <valid number>
}
}
things should work.