Postman - Possible to check Runner input file to dynamically create body? - javascript

I'm frequently using Postman to send requests to a Kanban API. However, the data being sent isn't always the same.
For example, the body of the request will always have an ID for the Kanban card to be added to the board, {{External_Card_ID}}, but it won't always have a plannedFinish or a title.
{
"customId": "{{External_Card_ID}}",
"title": "{{Title}}",
"plannedFinish": "{{Due_Date}}"
}
Is it possible to use pre-request scripts in Postman to check the CSV given to the runner to say something like
requestBody = "{
"customId":"{{External_Card_ID}}""
}"
If csvInput contains "Title" column then
append ",title":"{{Title}}" to requestBody
And then set the body to {{requestBody}}?

Solution found: use data.ColumnName

Related

How to specify JSON request body example in Postman Collection

I'm programmatically creating Postman collections and want to provide a default JSON request body to make requests easier.
I've looked through the spec can can't see how to specify it. Does anyone have any ideas? Could this be done with JavaScript, which I've used to automatically set headers and environment variables.
Here's the Postman Collection spec definition I'm working with, v2.1.0 draft 4:
https://schema.getpostman.com/collection/json/v2.1.0/draft-04/collection.json
https://schema.getpostman.com/
A request is specified by #/definitions/request.
The body is specified as one of the following. JSON isn't listed so raw is typically used. Here's an excerpt which appears shows that raw is a string type but there's no property to include a default value for the request body.
{
"body":{
"oneOf":[
{
"type":"object",
"description":"This field contains the data usually contained in the request body.",
"properties":{
"mode":{
"description":"Postman stores the type of data associated with this request in this field.",
"enum":[
"raw",
"urlencoded",
"formdata",
"file",
"graphql"
]
},
"raw":{
"type":"string"
}
}
}
]
}
}
Is anyone aware of Postman being able to specify an example for the JSON request body with a pre-created example, using the collection directly or via JavaScript?
UPDATE
The following YouTube video shows on the body can be set dynamically with JavaScript using the following.
const body = {
"productId": 1234
};
pm.globals.set("body", JSON.Stringify(body));
https://www.youtube.com/watch?v=hSX7Dcjy000
Using this approach, it seems the next thing to figure out is if the Postman Collection can import and access custom properties, e.g. x-properties, or if there's some other way to load the example content by overloading an existing property. It seems this can be done by loading a lot of environment variables, one for each request. The final step may be to be to automatically load the correct environment variable value into the example body when the user first brings up the endpoint.
Here's more information on a similar topic:
https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#scripting-with-request-data
The link you added is scripting withing postman test and pre request section , not for programmatically creating json.
You can open postman and click the inverted hamburger menu of collection to export the collection json. You can use this as reference.
In the generated json request is defined as : (Only url , method and body part not full )
"method": "DELETE",
"header": [],
"body": {
"mode": "raw",
"raw": "{{requestbody}}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{url}}/resource1/resource2",
"host": [
"{{url}}"
],
"path": [
"resource1",
"resource2"
]
}
This is the json created from postman.

How to append html formatted data from node js server to html file in client side?

I'm trying to build a site in plain javascript, node and handlebars that, trough a quote calculator, the user could request a list of several items to the owner of the site.
The data formatted in json such as:
{ "item": "candy", "brand":"delicious candy" }
would be inserted by the user in index.html.
The site then would perform some validations and then send it to the server through the fetch api attached to a event in a button somehow like 'send quote'
app.post('/api', (request, response) => {
let quote = request.body;
response.render('admin', quote);
Then HandleBars would insert the data in html such as:
<h1> Candy </h1>
<h2> Delicious candy </h2>
And here is where I'm stuck, I'm capable to visualize in the console the response of the api call, and apparently is sending back to the browser the data I want, but I cannot wrap my mind in how could I append this HTML to a HTML file called admin.html.
Are you at all familiar with jQuery? What you could do is create an empty paragraph tag in your Handlebars HTML.
<p id="candyData">
</p>
Then, in your JS file where you're adding your event listener for the submit button on your form, query the paragraph by ID.
const candyData = document.querySelector('#candyData');
Now, in your fetch to your server, it could look something like this to get the value to the page.
fetch('/url').then((response) => {
response.json().then((data) => {
if (data.error) {
candyData.textContent = data.error;
} else {
candyData.textContent = data.candyDataObj // candyDataObj should be accessed based on how you're storing the data.
}
});
});
Don't forget to also load in the script tag in your HTML file.
<script src="/scripts/app.js"></script> <!-- the src path should be updated per your directory -->

Hiding Carto Sql Api Key?

Currently i am loading a carto Table containing polyogns to my map on a php file using catro.js and the key is visible in javascript. Example given below is to call the sql api.
var layerStyle = $('#landuse-style').text();
cartodb.createLayer(CartoDbLib.map, {
user_name: 'sandyjones',
type: 'cartodb',
sublayers: [{
sql: "SELECT * FROM master " + query,
cartocss: layerStyle,
}],
extra_params: {
map_key: "myAPiKey"
}
}
how to hide this api key on my server using proxy php file or a backend php file if you can suggest a code example that i can use.
sometime back i tried but i was stuck with a problem that in the url of images from carto server will contain the map key.
I'm afraid you would need to create your own proxy. Here is a node.js-based proxy as sample: https://github.com/CartoDB/cartodb-api-proxy , but this is not supported code and probably it is even outdated.
If your table data is anyway public (and it will be public - via proxy also), then I'd define the table as "Public" in Carto web, then your app does not need to put API key to the request at all.

How to create append an array to a json value using (js/node/express)

I'm trying to re-create a CRUD app in NodeJs that I did using php/mysql etc, that takes a users form information and stores it in a file called "sample-data.json".
Essentially, with NodeJs a user fills in a form, front-end JS takes that info, passes it along to an api route I set up, and then using FS, writes that info to the sample-data.json file etc.
With the code below, once a users hits submit on the form, the code takes that info, and passes it to the "sampledataapi" route.
$("#createTodoForm").submit(function(evt){
evt.preventDefault();
$.post("/sampledataapi",{
todoCompany : $("#todoTitle").val(),
thisTodoIsFor : $("#todoIsFor").val(),
todoPostedBy : $("#todoPostedBy").val(),
todoCompleted : $("#todoCompleted").val(),
todoPriority : $("#todoPriority").val(),
todoMessages : $("#todoFirstMessage").val()
}, showDataGotten );
});
Once it saves the data, my sample-data.json file which initially has an empty array inside of it, then gets populated with info.
So sample-data.json goes from this: []
To this(once data has been entered):
[
{
"todoCompany":"sample company",
"thisTodoIsFor":"todo is for me",
"todoPostedBy":"admin",
"todoCompleted":"no",
"todoPriority":"green",
"todoMessages" : "sample message"
}
]
Now when I do this, all works fine but I run into problems when I want to have "todoMessages" be an array from the get go. Reason is that once the user posts their data, they will have the ability to erase/add messages from that block.
So I need that when the user submits the data, instead of that "todoMessages" being a regular string, I want it to be like this:
"todoMessages" : [ "sample message" ]
This way, I can push info into it OR delete from it etc.
How can I make it so that when the user creates his data, and the data passes the info to the route/json file, that it automatically creates todoMessages as an array?
I have tried (on front end)
todoMessages : [$("#todoFirstMessage").val()]
but then the front end reads "undefined"
and the backend json has this:
"todoMessages[]":"sample message"

webOS/Ares : read JSON from URL, assign to label

I've used the webOS Ares tool to create a relatively simple App. It displays an image and underneath the image are two labels. One is static, and the other label should be updated with new information by tapping the image.
When I tap the image, I wish to obtain a JSON object via a URL (http://jonathanstark.com/card/api/latest). The typcial JSON that is returned looks like this:
{"balance":{"amount":"0","amount_formatted":"$0.00","balance_id":"28087","created_at":"2011-08-09T12:17:02-0700","message":"My balance is $0.00 as of Aug 9th at 3:17pm EDT (America\/New_York)"}}
I want to parse the JSON's "amount_formatted" field and assign the result to the dynamic label (called cardBalance in main-chrome.js). I know that the JSON should return a single object, per the API.
If that goes well, I will create an additional label and convert/assign the "created_at" field to an additional label, but I want to walk before I run.
I'm having some trouble using AJAX to get the JSON, parse the JSON, and assign a string to one of the labels.
After I get this working, I plan to see if I can load this result on the application's load instead of first requiring the user to tap.
So far, this is my code in the main-assistant.js file. jCard is the image.
Code:
function MainAssistant(argFromPusher) {}
MainAssistant.prototype = {
setup: function() {
Ares.setupSceneAssistant(this);
},
cleanup: function() {
Ares.cleanupSceneAssistant(this);
},
giveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
},
jcardImageTap: function(inSender, event) {
//get "amount_formatted" in JSON from http://jonathanstark.com/card/api/latest
//and assign it to the "updatedBalance" label.
// I need to use Ajax.Request here.
Mojo.Log.info("Requesting latest card balance from Jonathan's Card");
var balanceRequest = new Ajax.Request("http://jonathanstark.com/card/api/latest", {
method: 'get',
evalJSON: 'false',
onSuccess: this.balanceRequestSuccess.bind(this),
onFailure: this.balanceRequestFailure.bind(this)
});
//After I can get the balance working, also get "created_at", parse it, and reformat it in the local time prefs.
},
//Test
balanceRequestSuccess: function(balanceResponse) {
//Chrome says that the page is returning X-JSON.
balanceJSON = balanceResponse.headerJSON;
var balanceAmtFromWeb = balanceJSON.getElementsByTagName("amount_formatted");
Mojo.Log.info(balanceAmtFromWeb[0]);
//The label I wish to update is named "updatedBalance" in main-chrome.js
updatedBalance.label = balanceAmtFromWeb[0];
},
balanceRequestFailure: function(balanceResponse) {
Mojo.Log.info("Failed to get the card balance: " + balanceResponse.getAllHeaders());
Mojo.Log.info(balanceResponse.responseText);
Mojo.Controller.errorDialog("Failed to load the latest card balance.");
},
//End test
btnGiveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
}
};
Here is a screenshot of the application running in the Chrome browser:
In the browser, I get some additional errors that weren't present in the Ares log viewer:
XMLHttpRequest cannot load http://jonathanstark.com/card/api/latest. Origin https://ares.palm.com is not allowed by Access-Control-Allow-Origin.
and
Refused to get unsafe header "X-JSON"
Any assistance is appreciated.
Ajax is the right tool for the job. Since webOS comes packaged with the Prototype library, try using it's Ajax.Request function to do the job. To see some examples of it, you can check out the source code to a webOS app I wrote, Plogger, that accesses Blogger on webOS using Ajax calls. In particular, the source for my post-list-assistant is probably the cleanest to look at to get the idea.
Ajax is pretty much the way you want to get data, even if it sometimes feels like overkill, since it's one of the few ways you can get asynchronous behavior in JavaScript. Otherwise you'd end up with code that hangs the interface while waiting on a response from a server (JavaScript is single threaded).

Categories

Resources