I am trying to validate the format of the data request call in postman. The data is of type uuid and relates to property id (shown below).
Would someone please be able to help with this?
This is my code:
var jsonData = JSON.parse(responseBody);
var Ajv = require('ajv'),
ajv = new Ajv ({logger: console}),
schemaResponse = {
"required": [
"id",
"ID",
],
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuidFormatCheck"
}
};
Code wise it is like this:
var currentSchPmExpTest;
pm.test('Schema is valid', function() {
//var data = pm.response.json();
ajv.addFormat('uuidFormatCheck', /^[0-9e-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
currentSchPmExpTest = "schemaResponse variable";
pm.expect(ajv.validate(schemaResponse, jsonData)).to.be.true;
});
The body response is:
{
"sfsid": "11c22abc-c11a-1df2-ba3a-123a456b78f1",
};
Given the example response body you provided:
{
"sfsid": "11c22abc-c11a-1df2-ba3a-123a456b78f1"
}
You could use AJV in Postman like this:
let schemaResponse = {
"type": "object",
"required": [
"sfsid"
],
"properties": {
"sfsid": {
"type": "string",
"pattern": "^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$"
}
}
};
pm.test('Schema is valid', function() {
pm.response.to.have.jsonSchema(schemaResponse)
});
Related
I have the following response body:
`
{
"timestamp": "2022-11-08T12:40:11.631Z",
"data": {
"version": "2.2",
"endpoints": [
{
"identifier": "credentials",
"role": "SENDER",
"url": "https://example.com/credentials65"
},
{
"identifier": "tokens",
"role": "RECEIVER",
"url": "https://example.com/tokens245"
},
{
"identifier": "tokens",
"role": "SENDER",
"url": "https://example.com/tokens353"
},
.......
For each identifier and role (in Postman tests session), i want to define variables automatically.
I tried the following for the first ones:
_.each(pm.response.json(), (responseBody) => {
if (responseBody.identifier['data'][1]['identifier'] === "credentials") {
pm.globals.set("credentials_url", responseBody.url)
}
else if (responseBody.identifier === "tariffs") {
pm.globals.set("tariffs_url", responseBody.url)
}
})
The problem is that i do not know how to call the "identifier" and the script do not enter in the if loop. Can anyone help?
const endpoints = pm.response.json().data.endpoints;
for (const endpoint of endpoints) {
const array = pm.globals.get(`${endpoint.identifier}_url`) ?? [];
array.push(endpoint.url);
pm.globals.set(`${endpoint.identifier}_url`, array);
}
You can access the URLs in the arrays by using pm.globals.get("tariffs_url"), pm.globals.get("credentials_url") etc. (it'll work for every identifier)
I am building a web-app and want to connect data from Quandl through its JSON API.
However, the JSON I get from quandl has the column names separate from the data itself, check below:
{
"datatable": {
"data": [
[
"AAPL",
"MRY",
"2020-12-31",
"2020-09-26",
"2020-09-26",
"2021-07-28",
-406000000,
323888000000,
325562500000
]
],
]
],
"columns": [
{
"name": "ticker",
"type": "String"
},
{
"name": "dimension",
"type": "String"
},
{
"name": "calendardate",
"type": "Date"
},
{
"name": "datekey",
"type": "Date"
},
{
"name": "reportperiod",
"type": "Date"
},
{
"name": "lastupdated",
"type": "Date"
},
{
"name": "accoci",
"type": "Integer"
},
{
"name": "assets",
"type": "Integer"
},
{
"name": "assetsavg",
"type": "Integer"
}
]
},
"meta": {
"next_cursor_id": null
}
}
When I use this data in Appsmith, it can not infer the column names. Is there a simple javascript code to combine the column names with the data? Thank you!
This is possible with a simple JS snippet, Now my code written is not that great but will work in this case (Can be optimised)
{{
function() {
let tableData = [];
_.map(_d.datatable.data, (v, i) => {
let set = {}
_.map(v, (x, k) => {
var obj = {[_d.datatable.columns[k].name]: x}
set = {...set, ...obj}
})
tableData.push(set)
})
}()
}}
In the above snippet _d is the data which you receive, We map the array value index with the given column index and create a new object out of it, Also since this is a multiline JS code, In Appsmith we need to write this inside an IIFE like above.
In given response snippet "parentName" type is sometimes null or sometimes string. How to check/write testcase to check the typeof string as well as null at a time.
tests["Verify parentName is string"] = typeof(jsonData.parentName) === "string" || null;
tests["Verify parentName is string"] = typeof(jsonData.parentName) === "string" || "null";
"demo": [
{
"id": 68214,
"specializationId": 286,
"name": "Radiology",
"parentName": null,
"primary": true
}
],
How to handle this kind of condition in postman (null & string).
I would not recommend if elseif in Postman test case. Postman has inbuilt feature for schema checking, you can use that and can achieve the same result without if else.
First, I'm considering following as a response:
{
"demo": [{
"id": 68214,
"specializationId": 286,
"name": "Radiology",
"parentName": null,
"primary": true
}]
}
Postman test should be:
var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
"properties": {
"parentName": {
"type":["string", "null"]
}
}
};
pm.test('Verify parentName is string', function() {
var resParentName = pm.response.json().demo[0].parentName;
pm.expect(ajv.validate(schema, {parentName: resParentName})).to.be.true;
});
Edit: Validate full response, not just first item. Also check if parentName is present in the response or not.
var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
"properties": {
"demo":{
"type": "array",
"items": {
"properties": {
"id":{ "type": "integer" },
"specializationId":{ "type": "integer" },
"name":{"type": "string"},
"parentName":{
"type":["string", "null"]
},
"primary":{"type": "boolean"}
},
"required": [ "parentName"]
}
}
}
};
pm.test('Validate response', function() {
pm.expect(ajv.validate(schema, pm.response.json())).to.be.true;
});
I´d like to create a JSON-Object for a Google API-Request. Only content is needed to change. My solution gives me an invalid JSON-Format and is more a hack. Is there an easier way to do this? Thank your for your hints.
The necessary format look like this:
{
"requests": [
{
"image": {
"content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
JS
var cvs = cvs.substring('data:image/png;base64,'.length);
var json1 = '{"requests":[{ "image":{ "content":"'
var json2 = '"}, "features": [{"type":"DOCUMENT_TEXT_DETECTION"}] } ]}'
var entireJson = json1 + cvs + json2;
var ocrImage = JSON.stringify(entireJson);
What you have done in your example is initializing a Javascript Object.
JSON.parse(object_string); is not necessary. You may initialize it directly:
var ocrImage = {
"requests": [
{
"image": {
"content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
console.log(ocrImage)
I've written the following tableau webconnector to pull data from an internal API, using earthquakeUSGS.html as a guideline (https://github.com/tableau/webdataconnector). The API returns json (see code below). I've been using the "Web data connector simulator 2.0" and all has been going well. I get the correct Table, however, Im unable to "Fetch Table Data". As this is my first js script, Im very sure that is were the error is. To iterate through the data I used the answer from Korijn in this post Iterate through nested json object array
The Problem: Is probably with the js iterator over the json object. If anyone can take a look at the json (below), and have a look at my iterator, I would greatly appreciate it. This is what makes it impossible for me to fetch data.
test.js
(function() {
// Create the connector object
var myConnector = tableau.makeConnector();
// Define the schema
myConnector.getSchema = function(schemaCallback) {
var cols = [{
id: "prog",
alias: "PrognosisTime",
dataType: tableau.dataTypeEnum.string
}, {
id: "start",
alias: "Start",
dataType: tableau.dataTypeEnum.date
}, {
id: "val",
alias: "Value",
dataType: tableau.dataTypeEnum.float
}];
var tableSchema = {
id: "table",
alias: "187",
columns: cols
};
schemaCallback([tableSchema]);
};
// Download the data
myConnector.getData = function(table, doneCallback) {
$.getJSON("http://myapi.com/119%2C7777/Flattened?start=today&end=today&timeZone=CET&asOf=now&aggregation=None", function(resp) {
var feat = resp.features,
tableData = [];
tableData.push(
{"table":feat.properties.table}
);
// Iterate over the JSON object
//var SeriesId = feat.SeriesId
for(var i = 0; i <feat.DataPoints.length; i++){
var PrognosisTime = feat.DataPoints.PrognosisTime;
var Start = feat.DataPoints.Start;
var Value = feat.DataPoints.Value;
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
// Create event listeners for when the user submits the form
$(document).ready(function() {
$("#submitButton").click(function() {
tableau.connectionName = "Neas"; // This will be the data source name in Tableau
tableau.submit(); // This sends the connector object to Tableau
});
});
})();
json from API
[
{
"SeriesId": 119,
"DataPoints": [
{
"PrognosisTime": null,
"Start": "2016-08-24T00:00:00",
"Value": 26.19
},
{
"PrognosisTime": null,
"Start": "2016-08-24T01:00:00",
"Value": 23.9
},
{
"PrognosisTime": null,
"Start": "2016-08-24T02:00:00",
"Value": 22.82
}
]
},
{
"SeriesId": 7777,
"DataPoints": [
{
"PrognosisTime": null,
"Start": "2016-08-24T00:00:00",
"Value": 36.39
},
{
"PrognosisTime": null,
"Start": "2016-08-24T00:15:00",
"Value": 28.81
},
{
"PrognosisTime": null,
"Start": "2016-08-24T00:30:00",
"Value": 24.28
}
]
}
]
The problem is this line:
var feat = resp.features
resp is an array from your JSON, there is nothing called features. So, simply iterate over resp (or feat = resp) and pull out your DataPoints array.