Validating JSON schema in Postman - postman

When using Postman I validate the JSON response like so:
tv4.addSchema(globalSchema);
const valResult = tv4.validate(data, schema);
// schema is an object, which is a subschema from the larger globalSchema
which works fine, except for the error reporting. The error object I get is missing dataPath and schemaPath, making it hard for my user to find out where the actual problem is. Is there a way to get those properties? (tried validateResult and validateMultiple to no avail)
As an alternative I tried ajv, but as I am in draft-04, it gives me errors. The advice from their site
var ajv = new Ajv({schemaId: 'id'});
// If you want to use both draft-04 and draft-06/07 schemas:
// var ajv = new Ajv({schemaId: 'auto'});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
does not work because the Postman sandbox does not allow me to require that… any thoughts?
See also: https://community.getpostman.com/t/json-schema-validation-troubles/5024

Here's how I validate schema's with postman to get more detailed errors:
const schema = {
};
var jsonData = JSON.parse(responseBody);
pm.test('Checking Response Against Schema Validation', function() {
var result=tv4.validateMultiple(jsonData, schema);
console.log(result);
pm.expect(result.valid).to.be.true;
});

Related

Converting Google Visualization Query result into JSON

I am a beginner trying to read a Google Sheet in a Javascript app using: https://docs.google.com/spreadsheets/d/mySheetID/gviz/tq?tq=Select%20*%20where%20A%20=%20%22Nan%22&tqx=out:JSON
I can access that row in my sheet and save it as JSON giving me a file with the content headed "/O_o/
google.visualization.Query.setResponse..." This is the file I cannot further process in javascript.
I see in: converting Google Visualization Query result into javascript array
that the solution appears to be: "If you add a header named X-DataSource-Auth in your request, the Visualization API will respond in JSON format". After a day of googling I am quite unable to find where I am supposed to put such a header and what its syntax should be.
But then I'm 82 years old and this stuff gets more difficult with each passing year... Can someone point me in the right direction?
once you receive the response from the query,
you can convert the response to a google data table.
var dataTable = response.getDataTable();
and the google data table has a method to convert the data table to JSON.
var jsonData = dataTable.toJSON();
this will return a JSON string.
if you then would like to work with the JSON using JavaScript,
you can parse the string...
jsonData = JSON.parse(jsonData);
the JSON will be an object with two properties, cols and rows.
you can see an example of the JSON result here...
see this fiddle for a working example using the following code...
https://jsfiddle.net/WhiteHat/5mu9wnbz/1/
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1M3wQgKg3JBF6_hzv1xWONP7HWVYoOvJ1jPbB27IUg94/gviz/tq?gid=0&headers=1');
query.send(function (response) {
if (response.isError()) {
console.log('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
};
var dataTable = response.getDataTable();
var jsonData = dataTable.toJSON();
jsonData = JSON.parse(jsonData);
document.getElementById('cols').innerHTML = jsonData.cols.length;
document.getElementById('rows').innerHTML = jsonData.rows.length;
console.log(jsonData);
});
});

Postman- How to save token value from Header Authorization

I have to create a series of GET - POST-GET request over Postman.
Here are the steps I am trying to implement:
1) GET - with base64 encoded authorization : through this I will get a token
2) POST - using the token received in Step1.
Now I want to know how can I save the token I am getting from step1 into an environment variable and further call the environment variable in step2.
Please refer to the Image to understand how I am receiving the token from step 1.
Below is how I am trying to save the variable in Tests,(not sure if this is correct)
var jsonData = JSON.parse(Headers);
pm.setEnvironmentVariable("token",jsonData.message.token);
As the reference looks like you're trying to get something from the response body, I'm assuming it looks something like this:
{
"message": {
"token": "qwerty123456"
}
}
In the script, you would use something like this:
var jsonData = pm.response.json();
pm.environment.set("token", jsonData.message.token);
One image, thousand words
Get global variable: {{token}}

Parse-Server Cloud Code Query Doesn't Return All Columns

I have setup Parse-Server on AWS Elastic Beanstalk by following this guide. I've then written a cloud-code function which fetches a single record from a specific class/collection. The collection contains about 20 columns. However, the object fetched as a result of the query contains only about 8 columns. I've made sure the record does have data in the columns which are missed by the query. Am I missing something here or is it some limitation in Parse? Is there any way to force Parse to fetch these columns?
Parse.Cloud.define('confirmAppointment', function(request, response) {
var staffId = request.params.staffId;
var appointmentId = request.params.appointmentId;
var appointmentRequest = Parse.Object.extend("AppointmentRequest");
appointmentRequest.id = appointmentId;
appointmentRequest.staffId = staffId;
var query = new Parse.Query(appointmentRequest);
query.first({
useMasterKey: true,
success: function(appointment) {
if (appointment) {
// these fields are not found in the fetched appointment object
// they do exist however in mongodb
var requesterUserId = appointment.get("requesterUserId");
var staffUserId = appointment.get("staffUserId");
var staffName = appointment.get("staffNameEn");
...
}
}
...
});
});
There might be some typos in your code (the construction of the query part). Try this instead:
Parse.Cloud.define('confirmAppointment', function(req, res) {
var staffId = req.params.staffId;
var appointmentId = req.params.appointmentId;
var query = new Parse.Query("AppointmentRequest");
query.equalTo('objectId', appointmentId);
query.equalTo('staffId', staffId);
query.first({
useMasterKey: true,
success: function(appointment) {
res.success(appointment.get("requesterUserId"));
},
error: function(err) {
res.error(err);
}
});
});
The issue turned out to be that when i did migration of data from Parse to my mongolab hosted MongoDB instance, I did not click 'Finalize' button in Parse migration wizard. That was intentional, as Parse was warning me that clicking Finalize would make the migration permanent and I would no longer be able to get back to the Parse managed database. On the other hand, I could see that all the data was successfuly migrated to mongolab, and technically it should have been enough to have my AWS hosted parse server work on this new database without any issue. But somehow, clicking "Finalize" button in Parse did some magic (I still dont understand what it could be) and my queries started returning the expected results.
I was able to reproduce the same issue when migrating to Heroku as well, so i was sure it had nothing to do with AWS.
Hope this would help someone.

Facebook graph API fail to load resource bad request 400

I have the following code on my controller.js and works when I request from Facebook Graph 2.4
request.open("GET","https://graph.facebook.com/v2.4/katyperry/posts?"+access_token,true);
However this only returns few fields: message, story, created_time, and id.
I need some additional more fields: message, picture, likes, created_time, link, type, comments and object_id.
So I tried the following:
request.open("GET","https://graph.facebook.com/v2.4/katyperry?fields=posts.limit(2){message,picture,likes,created_time,link,type,comments,object_id}"+access_token,true);
The last one sent me the error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
I tested both options the request on the Graph API Explorer and it worked properly. How can I get those extra fields? what am I missing?
I am adding the precedent code to show how access_token is builded:
var appID ="138429819833219";
var appSecret ="dada0a4d7f7717b0d37fd637d9e1522a";
var accessTokenRq = makeHttpRequest();
var httpString = 'https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id='+appID+'&client_secret='+appSecret;
accessTokenRq.open("GET",httpString,true);
accessTokenRq.send(null);
var access_token;
accessTokenRq.onreadystatechange = function() {
if (accessTokenRq.readyState == 4) {
access_token = accessTokenRq.responseText;
//alert("Hat geklappt - Trabajó :)");
var request = makeHttpRequest();
// the following request works
request.open("GET","https://graph.facebook.com/v2.2/katyperry/posts?"+access_token,true);
// next one don't - I checked inspector and access_token contains: 138429819833219|CewVrYOd86ctJ0HTP2X0XAS9m4o
request.open("GET","https://graph.facebook.com/v2.4/katyperry?fields=posts.limit(2){message,picture,likes,created_time,link,type,comments,object_id}"+access_token,true);
What is contained in the access_token variable? The request
/katyperry?fields=posts.limit(2){message,picture,likes,created_time,link,type,comments,object_id}
works in the Graph API Explorer, so I guess your access_token variable only contains the actual access token, and not the parameter key/value pair.
This
request.open("GET","https://graph.facebook.com/v2.4/katyperry?fields=posts.limit(2){message,picture,likes,created_time,link,type,comments,object_id}&access_token="+access_token,true);
should hopefully work then.
The error it was syntax, the right code as follow:
request.open("GET","https://graph.facebook.com/v2.4/katyperry/posts?limit=2&fields=message,picture,likes,created_time,link,type,comments,object_id&"+access_token,true);

How do I read a Django HTTPResponse in Flex?

I'm a complete Flex noob, so I apologize in advance if I'm missing something obvious.
I wrote a fairly simple file uploader in Flex, which calls my Django back-end via URLRequest (the FileReference object handles the upload). My upload works as intended and I have Django return a HTTPResponse object. As such, I'd like to read the contents of the HTTPResponse object.
Any thoughts?
something along the lines of
<mx:HTTPService id="myHTTPRequest"
url="{whatever your url request is}"
result="resultHandler(event)"
fault="faultHandler(event)"
showBusyCursor="true"
resultFormat="object">
then inside the resultHandler something like this
private function resultHandler (event : ResultEvent) : void {
var obj : Object = event.result;
//do something with returned object
}
Debug at the point of the resultHandler to see exaclty whats being returned, make sure its what you think should be getting returned.
By the time it gets to the client it's just a normal HTTP response so treat it like any other response
I am also new to flex and I ran in the same problem when doing an upload to a Java Rest backend, I solved it using the DateEvent on the FileReference. To get the response data use something like this.:
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
var request:URLRequest = new URLRequest("yourUrl");
fileRef.upload(request, "fileData");
private function responseHandler(event:DataEvent):void {
var response:XML = new XML(event.data);
//Note the DataEvent: this is the event that holds the response.
//I sent back data as xml
}
Your response should always be a successful HTTP status code (200), if your backend sends status 500 codes it will not trigger the DateEvent. Server errors can still be caught with a HTTPStatusEvent, but then you don't have access to the response.
you can access the response like so in your onComplete event handler:
private function saveCompleteHandler(event:Event):void {
var loader:URLLoader = event.currentTarget as URLLoader;
trace("saveCompleteHandler - event returned:" + loader.data as String);
}
we do this this to get json fron a java web service.
you just need to use a URLLoader to load the URLRequest in the first place:
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandler, 10000);
loader.addEventListener(IOErrorEvent.IO_ERROR, saveErrorHandler, 10000);
loader.addEventListener(Event.COMPLETE, saveCompleteHandler, 10000);
var request:URLRequest = new URLRequest("http:/whereverer");
request.method = URLRequestMethod.GET;
loader.load(request);