Consuming API in javascript without using Node.js - javascript

i am leveraging CamFind's API for image recognition in my windows phone 8 app. On their site they have given an example for how to use the API with Node.js.. however i am writing a PhoneGap Windows Phone app and dont have this availble.
I would like to use just plain jquery/javascript to use this API.
Here's the example provided on their site:
var Request = unirest.post("https://camfind.p.mashape.com/image_requests")
.headers({
"X-Mashape-Authorization": "Z**********************"
})
.send({
"image_request[locale]": "en_US",
"image_request[language]": "en",
"image_request[device_id]": "<image_request[device_id]>",
"image_request[latitude]": "35.8714220766008",
"image_request[longitude]": "14.3583203002251",
"image_request[altitude]": "27.912109375",
"focus[x]": "480",
"focus[y]": "640",
"image_request[image]": "/tmp/file.path"
})
.end(function (response) {
console.log(response);
});
Here's how i am trying to do the same using jquery/ 'plain' javascript
$.ajax({
url: 'https://camfind.p.mashape.com/image_requests', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
type: 'POST', // The HTTP Method
data: {
"image_request[locale]": "en_US",
"image_request[language]": "en",
"image_request[device_id]": "<image_request[device_id]>",
"image_request[latitude]": "35.8714220766008",
"image_request[longitude]": "14.3583203002251",
"image_request[altitude]": "27.912109375",
"focus[x]": "480",
"focus[y]": "640",
"image_request[image]": "http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg"
}, // Additional parameters here
datatype: 'json',
success: function(data) { alert(JSON.stringify(data)); },
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "Z**********************");
}
});
Issue/Question:
When i do it through javascript/jquery - it seems to be complaining about missing image_request[image] attribute. It never hits the success block.
Am i doing something wrong in terms of how i transformed the Node.js API request example (1st block of code above) provided by CamFind VS. how i am doing trying to consumer the API through plain through Javascript (2nd block of code above)?
Thanks!!
Fyi, references i am using:
Consume an API in javacstipt: https://www.mashape.com/imagesearcher/camfind#!endpoint-1-Image-Request
CamFind API usage: https://www.mashape.com/imagesearcher/camfind#!endpoint-1-Image-Request

I know this is an old question but having stumbled across it whilst trying to solve it myself I thought I should answer it for the future.
The issue is this line:
"image_request[image]": "http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg"
It should be:
"image_request[remote_image_url]": "http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg"
So the complete code is:
$.ajax({
url: 'https://camfind.p.mashape.com/image_requests', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
type: 'POST', // The HTTP Method
data: {
"image_request[locale]": "en_US",
"image_request[language]": "en",
"image_request[device_id]": "<image_request[device_id]>",
"image_request[latitude]": "35.8714220766008",
"image_request[longitude]": "14.3583203002251",
"image_request[altitude]": "27.912109375",
"focus[x]": "480",
"focus[y]": "640",
"image_request[remote_image_url]": "http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg"
}, // Additional parameters here
datatype: 'json',
success: function(data) { nowDoSomethingFun(data); },
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Key", "YOURKEY")
}
});
}

I am not familiar with this API but you might try formatting your data parameter like this:
data: {
image_request: {
locale: 'en_US',
language: 'en',
device_id: '<image_request[device_id]>',
latitude: '35.8714220766008',
longitude: '14.3583203002251',
altitude: '27.912109375',
image: 'http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg'
},
focus: {
x: '480',
y: '640'
}
}

Related

Cannot consume web service with JQuery (console issues cors but xml is returned) [duplicate]

This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 5 years ago.
I am trying to consume a web service with JQuery and I am getting the weird result of the browser showing cors error on the console while in the response tab I can see the returned XML.
See my console
See my response
The web service that I am trying to access calculate the freight of products.
I don't know how web services work, It's strange that it is blocked somehow, as the purpose of web services is to provide access to applications.
Here is the code I am trying to execute:
<script>
$().ready(function () {
var sendjson = {
"nCdEmpresa": "",
"sDsSenha": "",
"nCdServico": "41106",
"sCepOrigem": "37540000",
"sCepDestino": "37540000",
"nVlPeso": "1",
"nCdFormato": "1",
"nVlComprimento": "20",
"nVlAltura": "5",
"nVlLargura": "15",
"nVlDiametro": "0",
"sCdMaoPropria": "s",
"nVlValorDeclarado": "200",
"sCdAvisoRecebimento": "s"
}
$.ajax({
type: "GET",
cors: true,
url: "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo",
data: sendjson,
dataType: "application/xml",
success: function (data) {
console.log(data);
},
error: function (data, err)
{
alert(err);
}
});
});
</script>
If someone can give me directions how to consume this web services I will be very glad. The answer can be in C# too, using HttpClient or whatever.
you need to replace your ajax call parameters
cors : true to crossDomain: true,
dataType: 'application/xml' to contentType : 'application/xml'
Ajax Call :
$.ajax({
type: "GET",
crossDomain: true,
url: "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo",
data: sendjson,
contentType : 'application/xml',
success: function (data) {
console.log(data);
},
error: function (data, err)
{
alert(err);
}
});

U.N. FAO API - How do I do a POST data request via JS with this API?

I am trying to do a POST request (via JavaScript AJAX) to the United Nations Food and Agriculture Organization (U.N. FAO) API to get some data points. While I have successfully completed GET requests to this API with no problem, the POST requests continuously fail. I've done this type of request with many other APIs, but this one I can't figure out.
My code and URLs related to the API are below.
Can anyone please help me successfully complete a POST data request to this FAO API? Either modifying my code or creating your own example code would be fine.
The API endpoint is here:
http://fenixapps2.fao.org/api/v1.0/en/data/
The API's technical description is here:
http://fenixapps2.fao.org/api/v1.0/
The 'Example Page' for the API is here:
http://faostat.github.io/faostat-api/
The 'Showcase Page' for the API is here:
http://fenixapps.fao.org/repository/api/
My code -- a working GET request + non-working POST request -- is below.
You can cut-and-paste it into a text editor and it will work as an HTML file.
<html>
<head>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascript'>
function test() {
// (1) GET requests work fine.
// Based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
$.ajax({
type: 'GET',
url: 'http://fenixapps2.fao.org/api/v1.0/en/classifications/QC',
success: function(response) {
console.log("metadata GET response:");
console.log(response);
}
});
// (2) POST requests do NOT work with my code.
// Originally based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
// Modified per API description at: http://fenixapps2.fao.org/api/v1.0/
$.ajax({
url: "http://fenixapps2.fao.org/api/v1.0/en/data/",
traditional: true,
data: {
"datasource": "production", //test
"output_type": "objects", //arrays
"api_key": "n.a.",
"client_key": "n.a.",
"lang": "en",
//"domain_code":"QC", //domain_code (from example page - http://faostat.github.io/faostat-api/) replaced by domain_codes?
"domain_codes": ["'QC'"],
//"thousand_separator": ",", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
//"decimal_separator": ".", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
"decimal_places": "2",
"List1Codes": ["'33'"],
"List2Codes": ["'2510'"],
"List3Codes": ["'15'"],
"List4Codes": ["'2007'","'2008'","'2009'","'2010'","'2011'","'2012'","'2013'","'2014'"],
"List5Codes": null,
"List6Codes": null,
"List7Codes": null,
"null_values": true,
//"group_by"
//"order_by"
//"operator"
"page_size":"100",
"limit": "10",
"page_number":1
//"show_codes"
//"show_flags"
//"show_unit"
},
type: 'POST',
success: function(response) {
console.log("data POST response:");
console.log(response);
}
});
}
</script>
</head>
<body onload='test();'>
<div id='out'></div>
</body>
---UPDATE---
I have tried changing the data section within $.ajax() so that the url created exactly matches the format of that of the cURL example from the FAO 'Example' page (http://faostat.github.io/faostat-api/). However, this has not altered the API's response. My updated code is included below -- the new console.log(urlPlusData); line I believe should reflect the full url that the code is generating for the POST.
<html>
<head>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascript'>
function test() {
// (1) GET requests work fine.
// Based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
$.ajax({
type: 'GET',
url: 'http://fenixapps2.fao.org/api/v1.0/en/classifications/QC',
success: function(response) {
console.log("metadata GET response:");
console.log(response);
}
});
// (2) POST requests do NOT work with my code.
// Originally based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
// Modified per API description at: http://fenixapps2.fao.org/api/v1.0/
$.ajax({
url: "http://fenixapps2.fao.org/api/v1.0/en/data",
traditional: true,
data: {
"datasource": "production", //test
"output_type": "objects", //arrays
"api_key": "n.a.",
"client_key": "n.a.",
"lang": "en",
//"domain_code":"QC", //domain_code (from example page) replaced by domain_codes?
"domain_codes": ["QC"],
//"thousand_separator": ",", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
//"decimal_separator": ".", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
"decimal_places": "2",
"List1Codes": ["33"],
"List2Codes": ["2510"],
"List3Codes": ["15"],
"List4Codes": ["2007","2008","2009","2010","2011","2012"],
"List5Codes": ["null"],
"List6Codes": ["null"],
"List7Codes": ["null"],
"null_values": true,
//"group_by"
//"order_by"
//"operator"
"page_size":"100",
"limit": "10",
"page_number":"1"
//"show_codes"
//"show_flags"
//"show_unit"
},
beforeSend: function (jqXHR, settings) {
urlPlusData = settings.url + "?" + settings.data;
},
type: 'POST',
success: function(response) {
console.log("data POST response:");
console.log(urlPlusData);
console.log(response);
}
});
}
</script>
</head>
<body onload='test();'>
<div id='out'></div>
</body>

Trouble creating a folder in Box.com using jQuery?

I am building a web app using the Box API, but I'm having trouble simply creating a folder in the root directory. The token is set to a developer token which should be active.
The error I'm receiving now is Bad Request. What is wrong with this code? I'm also having trouble receiving authentication for the user, but I decided to tackle this first.
function createTestFolder() {
$.ajax('https://api.box.com/2.0/folders',
{
data: { name: 'CreatedFolderFromjQuery', parent: { id: '0' } },
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + window.token);
},
contentType: 'json',
success: function(data, status, xhr) {
alert(status);
},
error: function(xhr, status, error) { alert(error); }
});
}
EDIT : When I change the URL to https://box.com/api/1.0/folders, I seem to get a successful response. That is, the success function gets called, rather than the error function. However, the folder is still not uploaded to my account.
EDIT 2 : Using the curl command line and following the API documentation, I still receive the same error message. Here are the details:
{"type":"error", "status":400, "code":"bad_request", "context_info":{"errors":[{"reason":"invalid_parameter", "name":"entity_body", "message":"Invalid value ''{name:New Folder,'. Entity body should be a correctly nested resource attribute name/value pair"}]}, "help_url":"http://developers.box.com/docs/#errors", "message":"Bad Request", "request_id":"128521198353f4fc831c7e6"}
curl: (6) Could not resolve host: parent
curl: (3) [globbing] unmatched brace in column 1
curl: (3) [globbing] unmatched close brace/bracket in column 2
Ah, I have solved my own question. I am not familiar with jQuery, and here was my mistake:
data: { name: 'CreatedFolderFromjQuery', parent: { id: '0' } },
With jQuery's AJAX API, data needs to be a string. I needed to serialize my POST data into JSON:
data: JSON.stringify({ name: 'CreatedFolderFromjQuery', parent: { id: '0' } }),
Once I realized this, and added the JSON.stringify() the request was sent properly.

GitHub API results different between cURL and jQuery AJAX

I'm trying to query GitHub's search user API by language and location. When I use the command curl https://api.github.com/search/users?q=location:denver+language:php I receive 146 results. However, when I try to use jQuery AJAX, I receive an error.
My JavaScript code:
var url = "https://api.github.com/search/users";
var request = {
q: "location:denver+language:php",
sort: "repositories",
order: "desc"
};
var result = $.ajax({
url: url,
data: request,
dataType: 'jsonp',
type: 'GET'
})
.done(function() {
alert(JSON.stringify(result));
})
.fail(function() {
alert('failed');
});
What alert(JSON.stringify(result)); gives:
{
"readyState":4,
"responseJSON":{
"meta":{
"X-RateLimit-Limit":"10",
"X-RateLimit-Remaining":"9",
"X-RateLimit-Reset":"1397393691",
"X-GitHub-Media-Type":"github.beta",
"status":422
},
"data":{
"message":"Validation Failed",
"documentation_url":"https://developer.github.com/v3/search/",
"errors":[
{
"message":"None of the search qualifiers apply to this search type.",
"resource":"Search",
"field":"q",
"code":"invalid"
}
]
}
},
"status":200,
"statusText":"success"
}
When I only use one qualifier on q it works fine and the result.responseJSON.data object contains the information that is normally provided by cURL.
use a space character instead of a plus(+). Change your query to this:
q: "location:denver language:php",
and it will work as expected, because jquery will convert this space character to a plus.

ExtJS 4.2.1 mocking Ext.Ajax.request

For frontend unit testing with jasmine i want to mock all my requests in my application.
I've already implemented a method to mock all my proxies.
proxy: appname.classes.proxy.ProxyNegotiator.getModelProxy("User")
and this method does something like this:
getModelProxy: function(config) {
var url = this.getUrl(config);
if (this.getProxyType() == 'api') {
return appname.classes.proxy.WebApiProxy.getModelProxy(url);
} else if (this.getProxyType() == 'test') {
return appname.classes.proxy.LocalTestProxy.getModelProxy(url);
}
return undefined;
}
so you can imagine depending on my ProxyType configuration i get the web api proxy or the local proxy for testing. I do now have covered my crud operations..
Still, i do have another issue to deal with..
I do have some other requests in my application like this (validation of the username):
//check if Username is Valid
Ext.Ajax.request({
url: '/api/User',
method: 'GET',
async: false,
params: { id: user.get('Id'), username: user.get('UserName') },
failure: function(response, opts) {
myErrors.push({
field: 'UserName',
message: appname.locale.ErrorInvalidUsername
});
}
});
I do have some troubles with mocking this Ext.Ajax.request things... I've already searched in the web and did not find any nice solution for this.
Whats best practice to mock this request? I am glad about every hint and/or idea u can give me. Please HELP!
All versions of Ext JS starting with 4.0.7 ship with the Ext.ux.ajax.SimManager class. It's not included in the base library builds, but the unminified source is found under examples/ux/ajax of your Ext JS folder.
To use it, you register a URL with a Simlet configuration that defines your return data.
Ext.onReady(function () {
Ext.ux.ajax.SimManager.init({
delay: 500 // Simulates network latency/server processing time
}).register({
'/api/User': {
stype: 'json', // stype is what kind of Simlet you want to use
data: [
// JSON response data, if needed
]
}
});
});
Then you make your Ajax requests like normal and the SimManager will re-route the request through the registered Simlet.
I would check out sinon js to do your ajax mocking. We are currently using it to write unit tests in our Ext heavy application. http://sinonjs.org/docs/#fakeServer
You should be able to test your ajax request using something like this:
{
setUp: function () {
this.server = sinon.fakeServer.create();
},
tearDown: function () {
this.server.restore();
},
"test user" : function () {
this.server.respondWith("GET", "/api/User,
[500, { "Content-Type": "application/json" },
'[{ "id": 12, "comment": "Hey there" }]']);
Ext.Ajax.request({
url: '/api/User',
method: 'GET',
async: false,
params: { id: user.get('Id'), username: user.get('UserName') },
failure: function(response, opts) {
myErrors.push({
field: 'UserName',
message: appname.locale.ErrorInvalidUsername
});
}
});
this.server.respond();
//assert myErrors
}
}

Categories

Resources