how to format an API call with access token in JavaScript - json

I can't figure out how to make a request with an access token from JS. I have the API documentation here: https://littlesis.org/api
I'm using P5.js as well
this.url = 'https://littlesis.org/api/entities/search?q=' + this.name;
httpDo(
this.url, {
method: 'GET',
// Other Request options, like special headers for apis
headers: {
'Littlesis-Api-Token': 'xxxxx'
}
},
function(res) {
println("!");
}
);
This doesn't seem to work, and it gives me the following error: "NetworkError when attempting to fetch resource."
Is there a way to simply place the access token in the URL? That way I can retrieve the JSON the old fashion way.

Try adding a no-cors option to your request:
this.url = 'https://littlesis.org/api/entities/search?q=' + this.name;
httpDo(
this.url, {
method: 'GET',
mode: 'no-cors',
// Other Request options, like special headers for apis
headers: {
'Littlesis-Api-Token': 'xxxxx'
}
},
function(res) {
println("!");
}
);
At least for me, this changes the error from a 422 unproccessable entity error to a 401 unauthorized error, which I assume your actual API key will resolve.

Related

Google Scripts API - autoUpdateForwarding Not Applying

As Domain Admin for the company I work at we'd like to set the forwarding addresses of staff as they leave the company to ensure any important correspondence isn't missed.
I've used the Google Apps OAuth2 Library successfully so far, but come across a snag. The following code is meant to forward emails from the address apitest#example.com to newaddress#example.com .
function setupForwarding() {
var service = getOAuthService();
service.reset();
try {
if (service.hasAccess()) {
var header = {
Authorization: 'Bearer ' + service.getAccessToken(),
}
var url = "https://www.googleapis.com/gmail/v1/users/apitest#example.com/settings/autoForwarding";
var response = UrlFetchApp.fetch(url, {
headers: header,
method: 'put',
enabled: true,
emailAddress: 'newaddress#example.com',
disposition: 'trash'
});
Logger.log(response.getContentText());
}
} catch (e) {
Logger.log(e.message);
}
}
The access token provided appears to work with other queries provided by UrlFetchApp such as using it to return the currently authorised forwarding addresses recorded on the account (which does include newaddress#example.com) and doesn't report any access priviledge errors. The response returns only the following
{ "enabled" : false }
And does not apply any forwarding. Would someone be able to help me identify the problem? I feel I might be passing the parameters to the HTTP request incorrectly but I'm still learning my way around that system and no other questions I found seemed to help.
Ozzie
I worked this out and it was simpler than I thought; so sharing the answer here in case anyone has a similar issue.
var response = UrlFetchApp.fetch(url, {
headers: header,
method: 'put',
contentType : 'application/json',
payload: '{ "enabled" : "true" , "emailAddress" : "newaddress#example.com" , "disposition" : "trash" }'
});
Is the functional way to do this; the request was expecting a separate payload and declared content type both.

HTTP Request returning empty element

I try to get a JSON object from a webservice with
MashupPlatform.http.makeRequest(url, {
method: 'GET',
requestHeaders: {"Accept": "application/json"},
forceProxy: true,
onSuccess: function (response) {
console.log("response: " + JSON.stringify(response));
success(response);
},
onFailure: function (response) {
error(response);
},
onComplete: function () {
complete();
}
});
but in the console every time an empty element ({}) gets logged. If I use curl to request that exact same URL I get the response I need. Is the wirecloud proxy unable to request application/json? In my browsers network analysis I see the request including the correct response, but the success function seems to not get that data.
WireCloud proxy supports application/json without any problem. Although the problem may be caused by other parameters, I think that your problem is related to a bad access to the response data. You should use response.responseText instead of using directly the response object (see this link for more info).

Change User-Agent for XMLHttpRequest in TVML app

I'm working on an Apple TV app using TVMLKit. My app's JavaScript code tries to send an HTTP request to a server using XMLHttpRequest. The server is expecting a specific user agent, so I tried this:
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.setRequestHeader("User-Agent", "MyApp");
request.send();
The server receives a different User-Agent header:
User-Agent: <Projectname>/1 CFNetwork/758.1.6 Darwin/15.0.0
If I change the header name to something different, it shows up in the request headers. I guess Apple is replacing the User-Agent field right before sending the request. Is there a way to prevent this?
After spending two days on investigating this question I've came to solution with creating native GET and POST methods in swift end exposing them to javascript. This isn't best solution but still I want to share it. Maybe it could help someone.
Here how it works
First we need to install Alamofire library. We will use it for creating requests.
Readme on github has all instructions you need to install it
After installing Alamofire we need to import it in AppDelegate.swift
import Alamofire
Then we need to create function in app controller (AppDelegate.swift) that will expose methods to javascript
func appController(appController: TVApplicationController, evaluateAppJavaScriptInContext jsContext: JSContext)
{
let requests = [String : AnyObject]()
let get: #convention(block) (String, String, [String : String]?) -> Void = { (cId:String, url:String, headers:[String : String]?) in
Alamofire.request(.GET, url, headers: headers)
.responseString { response in
jsContext.evaluateScript("requests." + cId + "(" + response.result.value! + ")")
}
}
let post: #convention(block) (String, String, [String : AnyObject]?, [String : String]?) -> Void = { (cId:String, url:String, parameters:[String : AnyObject]?, headers:[String : String]?) in
Alamofire.request(.POST, url, parameters: parameters, headers: headers)
.responseString { response in
jsContext.evaluateScript("requests." + cId + "(" + response.result.value! + ")")
}
}
jsContext.setObject(requests, forKeyedSubscript: "requests");
jsContext.setObject(unsafeBitCast(get, AnyObject.self), forKeyedSubscript: "nativeGET");
jsContext.setObject(unsafeBitCast(post, AnyObject.self), forKeyedSubscript: "nativePOST");
}
Full code of AppDelegate.swift you can find here
All set! Now we have access to nativeGET and nativePOST functions from javascript.
The last thing is to make requests and retrieve responses. I haven't understand how to make callback executions in swift so I've used jsonp approach using runtime generated functions and passing their names to native functions.
Here how it looks in javascript
export function get(url, headers = {}) {
return new Promise((resolve) => {
const cId = `get${Date.now()}`;
requests[cId] = response => {
delete requests[cId];
resolve(response);
}
nativeGET(cId, url, headers);
});
}
export function post(url, parameters = {}, headers = {}) {
return new Promise((resolve) => {
const cId = `post${Date.now()}`;
requests[cId] = response => {
delete requests[cId];
resolve(response);
}
nativePOST(cId, url, parameters, headers);
});
}
The code above is written in ES6 and you'll need to include Promise polifill in your TVJS app.
Now we can make GET and POST requests applying any header we need
post('http://example.com/', {
login: 'xxx',
password: 'yyy'
}, {
'User-Agent': 'My custom User-Agent'
})

Web Api Rest method receives JObject wrapped in another JObject as a key value

I have problem with json which is sent from the sencha touch client to the rest web abi web service.
When i send POST request from Sencha it looks like:
var paramsData = Ext.encode({
FormId: '5',
WorkcardId: 'a1234',
FormDataSet: 'dataset'
});
Ext.Ajax.request({
url: JsonTestClient.app.webserviceUrl',
scope: this,
method: 'POST',
headers: { 'Authorization': 'Bearer ' + jsonToken.access_token },
params: paramsData,
contentType: "application/json;charset=utf-8",
success: function (response, options) {
//
},
failure: function (response, options) {
//
}
});
and paramsData value is : "{"FormId":"5","WorkcardId":"a1234","FormDataSet":"dataset"}"
However on WebApi RestService in the method
[System.Web.Http.HttpPost]
public string SaveForm([FromBody] JObject jsonData)
{
//
}
jsonData looks like
{
"{\"FormId\":\"5\",\"WorkcardId\":\"a1234\",\"FormDataSet\":\"dataset\"}": ""
}
So it seems like my initial json is wrapped in another object and is used as a key value.
Any ideas what can be wrong?
thanks.
From client site(sencha),Can you verify JSON in the http request body?
From server side,did you write all the contract for that method like what kind of parameter it can accept?
RequestFormat = WebMessageFormat.Json,
Above property should be placed inside the interface(or directly inside class if you did not have interface) that defines the contract regarding the input parameter.
Thanks to kasharma, i payed attention to how looks FormData in the sencha touch request.
From that i found a solution. I had to add
jsonData: paramsData,
to the post request

405 Method Not Allowed - Firebug error trying to retrive a JSON feed from Youttube with Mootools

Getting an error in firebug and obviously no feedback inline.
"NetworkError: 405 Method Not Allowed - http://gdata.youtube.com/feeds/api/playlists/67621C8899ABADA5?alt=json"
var loadVideos = function()
{
var req = new Request.JSON(
{
url: 'http://gdata.youtube.com/feeds/api/playlists/67621C8899ABADA5?alt=json',
method: 'get',
onSuccess: function(jsonData)
{
//successCode
}
}).send();
}
I don't understnad whats wrong, I can request that URL in a browser but Request.JSON cant?
You can't use 'simple' JSON request to retrieve data from other domains (see same origin policy). You should instead use JSONP
i.e.
var req = new Request.JSONP(
{
url: 'http://gdata.youtube.com/feeds/api/playlists/67621C8899ABADA5?alt=json',
method: 'get',
onSuccess: function(jsonData)
{
//successCode
}
}).send();