Given this GraphQL example, how can I in Javascript do a similar request with JSON?
Using GraphQL the query in the example is:
{
trip(
from: {place: "NSR:StopPlace:5533" },
to: {place:"NSR:StopPlace:5532"}
)
{
tripPatterns{duration}
}
}
According to the documentation the URL to query is https://api.entur.io/journey-planner/v2/graphql .
Here is what I tried in Javascript:
var url = "https://api.entur.io/journey-planner/v2/graphql";
var tripquery =
{
trip:
{
__args: {
from : {place :"NSR:StopPlace:5533" },
to : {place :"NSR:StopPlace:5532" }
},
tripPatterns: {
duration : true
}
}
};
function jsonQuery(){
var qry = JSON.stringify(tripquery);
var url_qry = url + "?query=" + qry;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url_qry, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function(){
console.log("onreadystatechange");
if(xhttp.readyState === 4 && xhttp.status === 200){
console.log("json-query-OK");
console.log(xhttp.responseText);
}
else{
console.log("xhttp.status : " + xhttp.status);
console.log("xhttp.statusText : " + xhttp.statusText);
console.log("xhttp.readyState : " + xhttp.readyState);
console.log("xhttp.responseType: " + xhttp.responseType);
console.log("xhttp.responseText: " + xhttp.responseText);
console.log("xhttp.responseURL : " + xhttp.responseURL);
console.log("json-not-ok");
}
};
xhttp.send();
console.log("query sent");
}
The code above will result in this output in the console:
query sent
api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}:1 POST https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}} 400 (Bad Request)
query.js:29 onreadystatechange
query.js:35 xhttp.status : 400
query.js:36 xhttp.statusText : Bad Request
query.js:37 xhttp.readyState : 2
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText:
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status : 400
query.js:36 xhttp.statusText : Bad Request
query.js:37 xhttp.readyState : 3
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status : 400
query.js:36 xhttp.statusText : Bad Request
query.js:37 xhttp.readyState : 4
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
The __args in the Json object is something I got from an example online, but I haven't really understood it.
Maybe I'm not sure what exactly to search for, but I can't find some good explanation of how to translate this GraphQL query to a JSON object.
I had the same problem and I did it like this:
{
c_con_tic_PTF(dz: CR, docmanId: 123) {
docmanId
dz
data
}
}
I tried sending this request as curl command in OS X How to use CURL in OS X:
curl \
-X POST \
-H "Content-Type: application/json" \
--data '{ "query": "{ c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }' \
*my-graphicQL endpoint url*
And I got the response I wanted.
So you want to make something like this from your graphQL query:
{ "query": "{ cz_atlascon_etic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }
And now just send request with JS.
If it helps you in any way, this is how my request looked in Java:
HttpRequest mainRequest =
HttpRequest.newBuilder()
.uri(URI.create("my graphQL endpoint"))
.POST(HttpRequest.BodyPublishers.ofString("{ \"query\": \"{ c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}\" }"))
.build();
One way to do it in Javascript is using the fetch api. Something like this is how I've done it in the past. You can test it out by copying the code below and then pasting it into Chrome Dev Tools and running it.
async function makeGraphQlQuery(urlToResource) {
const queryObject = {
query:
'{ trip( from: {place: "NSR:StopPlace:5533" }, to: {place:"NSR:StopPlace:5532"}) {tripPatterns{duration}} }',
};
const response = await fetch(urlToResource, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(queryObject),
});
const json = response.json();
return json;
}
async function sendAsync() {
const res = await makeGraphQlQuery('https://api.entur.io/journey-planner/v2/graphql');
console.log(res);
}
sendAsync().catch(err => console.log('Error in query', err));
Related
I seriously confused how to solve this multipart boundary when using Axios, react.js and multipart/formdata. I already stuck for 2 weeks to try to solve this but I feel like I getting closer to solved it but it still stuck no matter what solution I try.
I read and trysome solution from this topic:
how-to-post-multipart-formdata-using-fetch-in-react-native
how-to-send-multipart-form-data-with-antd-upload-react
how-to-send-a-multipart-form-data-from-react-js-with-an-image
this is my create Order function in orderAction.js :
function createOrder(data) {
return dispatch => {
let apiEndpoint = 'order';
let payload = new FormData();
// payload.append('orderImage', data.orderImage);
// console.log("Cek Image : ", data.orderImage);
for (const file of data.orderImage) {
payload.append('orderImage', file)
}
payload.append('userId', data.userId);
payload.append('materialId', data.materialId);
// payload.append('materialId', '5d79930c8c4a882f44b1b0fb');
payload.append('color', data.color);
payload.append('description', data.description);
payload.append('quantity', data.quantity);
payload.append('city', data.city);
payload.append('detailAddress', data.detailAddress);
console.log("Cek Data : ", payload);
fetch(config.baseUrl + apiEndpoint, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
'Content-Type' : 'multipart/form-data; boundary=----WebKitFormBoundaryHl8DZV3dBSj0qBVe'
},
body: payload
})
// orderService.post(apiEndpoint, payload)
// .then(res => {
// if(res.data.status === 200) {
// alert(res.data.Message);
// dispatch(createOrderSuccess(res.data));
// history.push('/user-order');
// } else {
// dispatch(createOrderFailed());
// alert(res.data.Message);
// }
// })
};
}
can someone help me to solve this? I'm quite confused with this problem
Edit 1
after try using #narasimha solution finally I got rid the multipart boundary but I got weird behaviour where The data succesfully got encoded like this:
but When I trying check the response the photoUrl return null or `` like this:
and when I try using insomnia or postman it successfully generated the photoUrl like this:
where did I wrong in here?
I had the same problem yesterday. The problem was with content type. I had used the same content type header as you are using. The thing is I removed content type and allowed the fetch () API to handle it automatically. It worked!!
Goal
Capture each event sent through a webhook and turn it into a Slack post. Events include new blog posts, questions, discussions, wiki page, etc. (qualified as contents) and comments (qualified as comments) posted in an online community. Sometimes multiple events are sent in the webhook at once.
Attempted method
This simple JavaScript Azure Function is intended to
Receive one or more webhook events sent in a JSON array
Filter objects qualified as contents from those qualified as comments
Send an API request for each content and/or comment object (both have their own URL endpoint)
Parse each object returned (contents and comments return a similar but different hierarchy of keys)
Assemble the values into JSON objects (one per event, regardless of whether it is a content or comment) and send to Slack
Results
The following code worked fine for a single webhook event until I attempted to add the for loop to accommodate multiple webhook events sent in one array.
Code
Example JSON from webhook
{
"events": [{
"TypeId": "9999-999e",
"DateOccurred": "2018-12-15T20:39:42.2487557Z",
"EventData": {
"ActorUserId": 1234,
"ContentId": "5678-999c",
"ContentTypeId": "9012-999d",
"WikiPageId": 3456,
"WikiId": 1
}
},
{
"TypeId": "1111-111f",
"DateOccurred": "2018-12-15T22:55:37.7846546Z",
"EventData": {
"ActorUserId": 2345,
"ContentId": "2222-222b",
"ContentTypeId": "3333-333a",
"ForumReplyId": 4567,
"ForumThreadId": 8901,
"ForumId": 2
}
},
{
"TypeId": "9012-888f",
"DateOccurred": "2018-12-15T22:44:57.7091846Z",
"EventData": {
"ActorUserId": 9876,
"CommentId": "8900-123a"
}
}
]
}
Example JSON returned from API request
The slightly different structure in hierarchies is accurate.
(for contents)
{
"Content": {
"CreatedByUser": {
"ProfileUrl": "https://<company>.telligenthosting.net/members/<user>",
"Username": "<user>"
},
"HtmlName": "Title",
"HtmlDescription": "Text",
"Url": "https://<company>.telligenthosting.net/<link>"
}
}
(for comments)
{
"Comment": {
"Content": {
"CreatedByUser": {
"ProfileUrl": "https://<company>.telligenthosting.net/members/<user>",
"Username": "<user>"
},
"HtmlName": "Title",
"HtmlDescription": "Text",
"Url": "https://<company>.telligenthosting.net/<link>"
}
}
}
JavaScript file (as an Azure Function)
module.exports = function (context, data) {
var json = data.body;
var request = require('request');
// Parse the webhook event JSON body
var unparsed = JSON.stringify(json.events);
var parsed = JSON.parse(unparsed);
console.log(parsed) // RESULTS ARE AS EXPECTED (the JSON nested beneath `events`, beginning and ending with `[]`)
for (var i = 0; i < parsed.length; i++) {
// Parse out Id of webhook event (for all content types but comments)
// This Id retrieves details about the content
var ContentId, ContentTypeId;
if (parsed[i].EventData.hasOwnProperty('ContentId')) {
var ContentId = parsed[i].EventData.ContentId;
var ContentTypeId = parsed[i].EventData.ContentTypeId;
console.log(ContentTypeId); // RESULTS ARE NOT AS EXPECTED: Prints the same Id twice
var options = {
url: "https://<company>.telligenthosting.net/api.ashx/v2/genericcontent/" + ContentId + "/" + ContentTypeId + ".json",
headers: {
"Rest-User-Token": "<token>",
"Content-Type": "application/json"
}
};
};
// Parse out Id of a webhook event (for comments only)
// This Id retrieves details about a comment
var CommentId;
if (parsed[i].EventData.hasOwnProperty('CommentId')) {
var CommentId = parsed[i].EventData.CommentId;
var options = {
url: "https://<company>.telligenthosting.net/api.ashx/v2/comments/" + CommentId + ".json",
headers: {
"Rest-User-Token": "<token>",
"Content-Type": "application/json"
}
};
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
//For all content types but comments
var username, profileUrl, subject, url, text;
if (info.hasOwnProperty('Content')) {
username = info.Content.CreatedByUser.Username;
profileUrl = info.Content.CreatedByUser.ProfileUrl;
subject = info.Content.HtmlName;
url = info.Content.Url;
text = info.Content.HtmlDescription;
};
//For comments
if (info.hasOwnProperty('Comment')) {
username = info.Comment.User.DisplayName;
profileUrl = info.Comment.User.ProfileUrl;
subject = info.Comment.Content.HtmlName;
url = info.Comment.Url;
text = info.Comment.Body;
};
};
//Send to Slack
function sendToSlack(theUsername, theIconEmoji) {
var theUsername = "Bot";
var theIconEmoji = ":bot:";
var payload = {
attachments: [{
author_name: username,
author_link: profileUrl,
title: subject,
title_link: url,
text: text
}]
};
if (theUsername !== undefined) {
payload.username = theUsername;
}
if (theIconEmoji !== undefined) {
payload.icon_emoji = theIconEmoji;
}
var theRequest = {
url: urlWebHook,
method: "POST",
json: payload
};
request(theRequest, function (error, response, body) {});
}
var urlWebHook = "https://hooks.slack.com/services/<Id>";
sendToSlack();
};
};
request(options, callback);
};
Issue
As commented out in the code above, it appears that the loop is not going through each event but rather through the first event multiple times.
Much of what I read indicates for (var i = 0; i < json.length; i++) { is the proper approach but no matter what I try the Azure Function throws a 500 Internal Service Error and eventually times out. No information is provided in the debug console even though detailed logging is turned on.
Thank you
Thank you for any advice or education.
EventData is not defined because you're not constructing your object properly.
Here's how you might do it:
var json = require("./test.json");
var unparsedEvents = json.events;
for (let event of unparsedEvents) {
var ContentId = event.EventData.ContentId;
var ContentTypeId = event.EventData.ContentTypeId;
var CommentId = event.EventData.CommentId;
var options = new Object();
console.log("ContentId:", ContentId);
console.log("ContentTypeId:", ContentTypeId);
console.log("CommentId:", CommentId);
if (CommentId) {
options.url = "https://<company>.telligenthosting.net/api.ashx/v2/comments/" + CommentId + ".json";
options.headers = {
"Rest-User-Token": "<token>",
"Content-Type": "application/json",
};
} else {
options.url = "https://<company>.telligenthosting.net/api.ashx/v2/genericcontent/" + ContentId + "/" + ContentTypeId + ".json";
options.headers = {
"Rest-User-Token": "<token>",
"Content-Type": "application/json",
};
}
console.log("options:", options);
console.log();
}
I believe you need to change parsed[0] to parsed[i]. Currently you are looping through the array but only accessing the first element, which is why you see the first event multiple times.
I'm trying to post a tweet but for any reason it doesn't work as expected.
I suspect that the issue could be related to the signature string, but following what twitter says according to signing requests looks ok.
Here is my code:
function postTweet(user_id, AccessToken, AccessTokenSecret) {
var base_url = 'https://api.twitter.com/1.1/statuses/update.json',
oauth_nonce = randomString(),
oauth_signature,
oauth_timestamp = Math.floor(new Date().getTime() / 1000),
reqArray,
req,
signature_base_string,
signing_key;
reqArray = [
"include_entities=true",
'oauth_consumer_key="' + CONFIG.TWITTER_CONSUMER_KEY + '"',
'oauth_nonce="' + oauth_nonce + '"',
'oauth_signature_method="HMAC-SHA1"',
'oauth_timestamp="' + oauth_timestamp + '"',
'oauth_token="' + AccessToken + '"',
'oauth_version="1.0"',
'status=' + encodeURIComponent("hello world")
];
req = reqArray.sort().join('&');
signature_base_string = "POST&" + encodeURIComponent(base_url) + "&" + encodeURIComponent(req);
signing_key = CONFIG.TWITTER_CONSUMER_KEY_SECRET + '&' + AccessTokenSecret;
oauth_signature = encodeURIComponent(CryptoJS.HmacSHA1(signature_base_string, signing_key).toString(CryptoJS.enc.Base64));
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: 'hello world'
}).then(function (response) {
return response;
}).catch(function (error) {
console.log(error);
});
}
As a response, I get that:
UPDATE
considering that in my project I already have $cordovaOauthUtility I started using it this way:
function postTweet(accessToken, accessTokenSecret) {
var params, signature;
params = {
include_entities: true,
oauth_consumer_key: CONFIG.TWITTER_CONSUMER_KEY,
oauth_nonce: $cordovaOauthUtility.createNonce(10),
oauth_signature_method: "HMAC-SHA1",
oauth_token: accessToken,
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_version: "1.0"
};
signature = $cordovaOauthUtility.createSignature('POST', 'https://api.twitter.com/1.1/statuses/update.json', params, { status: "hello" }, CONFIG.TWITTER_CONSUMER_KEY_SECRET, accessTokenSecret);
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: "hello"
}, {
headers: {
Authorization: signature.authorization_header
}
})
.then(function (response) {
return response;
}).catch(function (error) {
console.log(error);
});
}
UPDATE 2
After trying all the posibilities, the problem persist. Here I paste a plnkr where I have my code.
You are using crypto's HmacSHA256 but sending HMAC-SHA1 as the oauth_signature_method parameter which is the twitter one.
You should probably change your code to
oauth_signature = CryptoJS.HmacSHA1(signature_base_string, signing_key).toString(CryptoJS.enc.Base64);
If you look at your authorization header, you can also notice that something is wrong with it. Indeed, you can see that the oauth_nonce and the oauth_version are prefixed by a & sign, which shouldn't be the case and most likely mean to the api you are not specifying them. It probably comes from the fact you are using the same reqArray to construct both the signature and the header, or your code is not updated.
You also probably don't want to change the global headers sent from your app, in case another request is sent to another api at the same time. Rather, you should send this authorization header only for this specific xhr.
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: 'hello world',
}, {
headers: {
Authorization: auth,
},
})
Well, you're clearly adding oauth_token in your request array but it didn't show up in the screenshot? Is the AccessToken in the params undefined?
EDIT
According to the documentation, we must append double quotes to the headers. Try this?
reqArray = [
"include_entities=true",
'oauth_consumer_key="'+CONFIG.TWITTER_CONSUMER_KEY+'"',
'oauth_nonce="'+oauth_nonce+'"',
'oauth_signature_method="HMAC-SHA1"',
'oauth_timestamp="'+oauth_timestamp+'"',
'oauth_token="'+AccessToken+'"',
'oauth_version="1.0"',
'status='+encodeURIComponent("hello world")
];
Yikes.
I've downloaded your plnkr bundle and added a read only application key set. I only had to set up and make one change to get a {"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."} response. Initially I was receiving {"errors":[{"code":32,"message":"Could not authenticate you."}]}.
Remove status: "hello" from between the curly brackets { } where you create your signature.
signature = $cordovaOauthUtility.createSignature('POST', 'https://api.twitter.com/1.1/statuses/update.json', params, { }, twitter.consumer_secret, twitter.access_token_secret);
My request headers become the following:
:authority:api.twitter.com
:method:POST
:path:/1.1/statuses/update.json
:scheme:https
accept:application/json, text/plain, */*
accept-encoding:gzip, deflate, br
accept-language:en-US,en;q=0.8
authorization:OAuth oauth_consumer_key="x",oauth_nonce="QFMmqiasFs",oauth_signature_method="HMAC-SHA1",oauth_token="y",oauth_timestamp="1496340853",oauth_version="1.0",oauth_signature="7Ts91LKcP%2FrYsLcF5WtryCvZQFU%3D"
content-length:18
content-type:application/json;charset=UTF-8
origin:http://localhost
referer:http://localhost/twits/
user-agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36
Googling eventually led me to a tutorial:
Displaying the Twitter Feed within Your Ionic App. I noted his general createTwitterSignature function does not take parameters and tweaked your code similarly.
function createTwitterSignature(method, url) {
var token = angular.fromJson(getStoredToken());
var oauthObject = {
oauth_consumer_key: clientId,
oauth_nonce: $cordovaOauthUtility.createNonce(10),
oauth_signature_method: "HMAC-SHA1",
oauth_token: token.oauth_token,
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_version: "1.0"
};
var signatureObj = $cordovaOauthUtility.createSignature(method, url, oauthObject, {}, clientSecret, token.oauth_token_secret);
$http.defaults.headers.common.Authorization = signatureObj.authorization_header;
}
I've read conflicting things about why there should/shouldn't be other parameters there, but I believe the signature is just supposed to be the basis of access and doesn't hash in every operation you want to perform - see Understanding Request Signing For Oauth 1.0a Providers.
I am trying to integrate Plaid via Stripe. Bear with me as I am not very familiar with javascript.
I want to know how I can place in to a PHP variable the public_token and account_ID so that I may include in the curl call.
JS
<button id='linkButton'>Open Plaid Link</button>
<script src="https://cdn.plaid.com/link/stable/link-initialize.js"></script>
<script>
var linkHandler = Plaid.create({
env: 'tartan',
clientName: 'Stripe / Plaid Test',
key: '[Plaid key]',
product: 'auth',
selectAccount: true,
onSuccess: function(public_token, metadata) {
// Send the public_token and account ID to your app server.
console.log('public_token: ' + public_token); // HOW DO I PLACE THIS IN PHP/curl?**
console.log('account ID: ' + metadata.account_id); // HOW DO I PLACE THIS IN PHP/curl?**
},
});
PHP/CURL
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://tartan.plaid.com/exchange_token',
CURLOPT_POST => true,
CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
),
CURLOPT_POSTFIELDS => http_build_query(array(
'client_id' => '[Plaid client ID]',
'secret' => '[Plaid secret]',
'public_token' => '[Plaid Link public_token]', // HOW DO I CREATE A VARIABLE FROM THE ABOVE JS ( console.log('public_token: ' + public_token);) to place here**
'account_id' => '[Plaid Link account_id]', // HOW DO I CREATE A VARIABLE FROM THE ABOVE JS ( console.log('public_token: ' + public_token);) to place here
)),
));
You will want to take a look at using XMLHTTP, also known as AJAX. This allows Javascript to make HTTP requests with post or get. If this looks too difficult, you can use the jQuery.ajax method (but you need to include jQuery in your HTML). You will then be able to point the request to your PHP page in which you make your cURL request and retrieve the values via _POST or _GET.
Examples as per below:
XMLHTTP REQUEST
var url = 'curl.php?token='+public_token+'&acctid='+metadata.account_id;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xmlhttp.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
JQUERY.AJAX
Assuming jQuery is included and jQuery.noConflict() has not been called.
$.ajax({
method: "GET",
url: "curl.php",
data: {
token: public_token,
acctid: metadata.account_id
}
}).done(function( msg ) {
console.log( msg );
});
Both examples above are only theoretical and untested, although I believe they should work. From here, you should be able to get the variables in your PHP like so:
'public_token' => $_GET['token'],
'account_id' => $_GET['acctid']
I am using swagger with servicestack but I am getting a 401 unauthorised error from my /resources URL becuase it requires an API key.
Unless I'm mistaken, according to the documentation I should set supportHeaderParams to true as well as the apiKeyName and apiKey value in the JSON parameters when initializing Swagger from my html page.
I was then expecting to see my API key in the http request headers, but it is still being appended to the URL and not in the headers collection.
Here is the code that initialises Swagger in my HTML page:
window.swaggerUi = new SwaggerUi({
discoveryUrl: "http://pathtomyservice.com/resources",
headers: { "testheader" : "123" },
apiKey: "123",
apiKeyName: "Api-Key",
dom_id:"swagger-ui-container",
supportHeaderParams: true,
supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
onComplete: function(swaggerApi, swaggerUi){
if(console) {
console.log("Loaded SwaggerUI");
console.log(swaggerApi);
console.log(swaggerUi);
}
$('pre code').each(function(i, e) {hljs.highlightBlock(e)});
},
onFailure: function(data) {
if(console) {
console.log("Unable to Load SwaggerUI");
console.log(data);
}
},
docExpansion: "none"
});
Unfortunately I get no headers at all, no 'Api-Key' or 'testheader'.
I think that it might be a bug in swagger ui.
As a workaround, I added the following in in the swagger index.html file.
$(function () {
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader("YourApiKeyHeader", $("#input_apiKey").val());
}
});
});
Hope this helps,
In swagger-ui 2.0 or greater, this is trivial:
https://github.com/wordnik/swagger-ui#header-parameters
// add a new ApiKeyAuthorization when the api-key changes in the ui.
$('#input_apiKey').change(function() {
var key = $('#input_apiKey')[0].value;
if(key && key.trim() != "") {
window.authorizations.add("key", new ApiKeyAuthorization("api_key", key, "header"));
}
})
This is also much more extensible and supports custom authentication mechanisms.
you can try this
(function () {
$(function () {
var basicAuthUI =
'<div class="input"><input placeholder="username" id="input_username" name="username" type="text" size="10"/></div>' +
'<div class="input"><input placeholder="password" id="input_password" name="password" type="password" size="10"/></div>';
$(basicAuthUI).insertBefore('#api_selector div.input:last-child');
$("#input_apiKey").hide();
$('#input_username').change(addAuthorization);
$('#input_password').change(addAuthorization);
});
function addAuthorization() {
SwaggerApi.supportHeaderParams = true;
SwaggerApi.headers = {"authentication": "test"};
var username = $('#input_username').val();
var password = $('#input_password').val();
if (username && username.trim() != "" && password && password.trim() != "") {
var basicAuth = new SwaggerClient.PasswordAuthorization('basic', username, password);
window.swaggerUi.api.clientAuthorizations.add("basicAuth", basicAuth);
console.log("authorization added: username = " + username + ", password = " + password);
}
}
})();