rescuegroup/Petfinder jQuery API requests - javascript

I am currently trying to get API responses from the two following API's. All of the sample code on their website is in PHP and asks for a token and token SSH, while they only give you an API key. Very lost trying to get requests to pull. The closest I've gotten is an error that says the following:
{status: "error", message: "Unable to read your data; it might not be in json format."}
here is my JS:
jQuery.get({
url: 'https://api.rescuegroups.org/http/v2.json',
type: 'post',
contentType: 'application/json',
data: {
apikey: 'XXXXXXX',
objectType:'animals',
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Any help is greatly appreciated. Really want to avoid having to learn PHP as I'm still very new to JS.

the problem is that you are not passing it as json.
this is json format.
let dataObject = {
data: {
apiKey: "xxxx"
}
};
let data = JSON.stringify(dataObject);
{
"data": {
"apikey": "xxx"
}
}
then pass data as your data.
After trying it with Postman the request went through.
Obviously I don't have the api key
{
"status": "error",
"message": "Error with your login credentials",
"messages": {
"generalMessages": [
{
"messageID": "1101",
"messageCriticality": "error",
"messageText": "Error with your login credentials."
}
],
"recordMessages": []
}
}

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);
}
});

Gmail API messages.get not returning expected data

I'm trying to write an embedded gmail client and have been following through the API documentation on the developer site, but I am unable to get message data in my response. I am able to list labels no problem (using the code from the API docs) so I know it is authenticating ok. I am also able to get message IDs.
When I try to get actual message data, I am running into an issue where the returned Object does not have the data I expect. I check this by logging the messageRequest data to the console because message payload didn't exist when I was initially trying to access it.
function displayInbox() {
var request = gapi.client.gmail.users.messages.list({
'userId': 'me',
'labelIds': 'INBOX',
'maxResults': 10
});
request.execute(function(response) {
$.each(response.messages, function() {
var messageRequest = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': this.id,
'format': 'full'
});
console.log(JSON.stringify(messageRequest,null,4));
messageRequest.execute(appendPre);
});
});
}
From developer console I get this output:
(index):473 {
"Mq": 1,
"Zq": {
"QT": null,
"k5": {
"path": "/gmail/v1/users/me/messages/15f3a370bc482a7a",
"method": "GET",
"params": {
"format": "full"
},
"headers": {},
"root": "https://www.googleapis.com",
"apiId": "gmail:v1"
},
"Ida": "auto",
"Uja": false,
"Tja": false
}
}
Thanks for any help.
You are currently doing JSON.stringify on the request object. What you are seeing in the console is not the response.
Try and wait for the messageRequest to finish asynchronously, and log the response in the callback instead:
var messageRequest = gapi.client.gmail.users.messages.get({
userId: 'me',
id: this.id,
format: 'full'
});
messageRequest.execute(function(response) {
console.log(response);
});

EWS - A token was not recognized in the JSON content

I try to send an email via EWS using Javascript and the REST API.
The OAuth is not the problem so far.
The problem is, if I try to send the email, the Server sends this response:
"{"error":{"code":"RequestBodyRead","message":"Invalid JSON. A token was not recognized in the JSON content."}" (taken from Chrome Debug Console).
Here my Javascript, where the error occurs:
function mailIsRaus(token) {
var gottenParam = JSON.stringify(token);
var jsonObj = JSON.parse(gottenParam);
var leToken = jsonObj['access_token'];
//This is the Token from Active Directory
leToken = "Bearer " + leToken;
var Message = {
"Message": {
"Subject": "TESTING REST API EWS",
"Body": {
"ContentType": "Text",
"Content": "IT WORKED. The EWS is working my friend."
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "johndoe#something.com"
}
}
]
},
"SaveToSentItems": "true"
};
//eMailData = JSON.stringify(eMailData);
$.ajax({
type: 'POST',
beforeSend: function (request) {
request.setRequestHeader("Authorization", leToken);
request.setRequestHeader("Content-Type", "application/json");
},
data: Message,
url: 'https://outlook.office.com/api/v2.0/me/sendmail',
success: function (e) {
console.log('Email sent');
console.log(e);
},
error: function (message) {
console.log(message);
}
});
}
I strictly sticked to MSDN and now, I have no clue, why this error occurs.
If I comment out the "setRequestHeader" I get an error 401 unauthorized.
The token ist correct.
The scope is also correct.
Maybe I made an simple mistake in the "var Massage" or something...
I found the solution by myself.
I had to uncomment the following line of code to:
eMailData = JSON.stringify(eMailData);
Now it is working fine.

Consuming API in javascript without using Node.js

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'
}
}

How to send data to a web Service Using Winj.xhr

I am new in Winjs coding I have data in a list .
and i want to send that data to my json Web Service .
I have a success to call to web service and i have the response so the web service is
working but the data doesn't seem to be sent. I dont know how to declare the data.
I have many data to sent like(username,first_name,last_name,password) to my Register.json
The Register.json have this response after the execution:
{
"format":
"json",
"success":
false,
"errors":
["User name is empty"],
"result":
null
}
so i m sure that data doesnt be sent
function Register() {
var dataArray = [
{
username: "Marley",
first_name: "dog",
last_name: "ded",
password: "pdre4252d"
}];
WinJS.xhr({
url: "my_Base_URL/Register.json",
type: "post",
headers: { "Content-type": "application /x-www-form-urlencoded" },
data: dataArray
// data:JSON.stringify(dataArray)
}).done(
function complete(result) {
if (result.status === 200) {
console.log("Success: Response Text: " + result.responseText);
}
else {
console.log("Fail:Response Text: " + result.responseText);
}
},
function error(error) {
console.log("error");
},
function progress(result) {
}
);
}
I will be thinkful if someone give me some help.
The WinJS.xhr() is a promise wrapper around XMLHttpRequest, which means it delegates your parameters to an XMLHttpRequest object and returns a WinJS.Promise object. The parameters may not be delegated correctly so play with adding and empty string for a username and such. Otherwise you can mimic the same functionality by creating your own WinJS.Promise with an XMLHttpRequest inside.

Categories

Resources