Make dynamic name text field in Postman - json

I'm using Postman to make REST API calls to a server. I want to make the name field dynamic so I can run the request with a unique name every time.
{
"location":
{
"name": "Testuser2", // this should be unique, eg. Testuser3, Testuser4, etc
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}

In Postman you want to use Dynamic Variables.
The JSON you post would look like this:
{
"location":
{
"name": "{{$guid}}",
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
Note that this will give you a GUID (you also have the option to use ints or timestamps) and I'm not currently aware of a way to inject strings (say, from a test file or a data generation utility).

In Postman you can pass random integer which ranges from 0 to 1000, in your data you can use it as
{
"location":
{
"name": "Testuser{{$randomInt}}",
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}

Just my 5 cents to this matter. When using randomInt there is always a chance that the number might eventually be present in the DB which can cause issues.
Solution (for me at least) is to use $timestamp instead.
Example:
{
"username": "test{{$timestamp}}",
"password": "test"
}

For anyone who's about to downvote me this post was made before the discussion in comments with the OP (see below). I'm leaving it in place so the comment from the OP which eventually described what he needs isn't removed from the question.
From what I understand you're looking for, here's a basic solution. It's assuming that:
you're developing some kind of script where you need test data
the name field should be unique each time it's run
If your question was more specific then I'd be able to give you a more specific answer, but this is the best I can do from what's there right now.
var counter = location.hash ? parseInt(location.hash.slice(1)) : 1; // get a unique counter from the URL
var unique_name = 'Testuser' + counter; // create a unique name
location.hash = ++counter; // increase the counter by 1
You can forcibly change the counter by looking in the address bar and changing the URL from ending in #1 to #5, etc.
You can then use the variable name when you build your object:
var location = {
name: unique_name,
branding_domain_id: 'however-you-currently-get-it',
parent_id: 'however-you-currently-get-it'
};

Add the below text in pre-req:
var myUUID = require('uuid').v4();
pm.environment.set('myUUID', myUUID);
and use the myUUID wherever you want
like
name: "{{myUUID}}"
It will generate a random unique GUID for every request

var uuid = require('uuid');
pm.globals.set('unique_name', 'testuser' + uuid.v4());
add above code to the pre-request tab.
this was you can reuse the unique name for subsequent api calls.
Dynamic variable like randomInt, or guid is dynamic ie : you donot know what was send in the request. there is no way to refer it again, unless it is send back in response. even if you store it in a variable,it will still be dynamic
another way is :
var allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var shuffled_unique_str = allowed.split('').sort(function(){return 0.5-Math.random()}).join('');
courtsey refer this link for more options

Related

How can I create an EMR cluster resource that uses spot instances without hardcoding the bid_price variable?

I'm using Terraform to create an AWS EMR cluster that uses spot instances as core instances.
I know I can use the bid_price variable within the core_instance_group block on a aws_emr_cluster resource, but I don't want to hardcode prices as I'd have to change them manually every time the instance type changes.
Using the AWS Web UI, I'm able to choose the "Use on-demand as max price" option. That's exactly what I'm trying to reproduce, but in Terraform.
Right now I am trying to solve my problem using the aws_pricing_product data source. You can see what I have so far below:
data "aws_pricing_product" "m4_large_price" {
service_code = "AmazonEC2"
filters {
field = "instanceType"
value = "m4.large"
}
filters {
field = "operatingSystem"
value = "Linux"
}
filters {
field = "tenancy"
value = "Shared"
}
filters {
field = "usagetype"
value = "BoxUsage:m4.large"
}
filters {
field = "preInstalledSw"
value = "NA"
}
filters {
field = "location"
value = "US East (N. Virginia)"
}
}
data.aws_pricing_product.m4_large_price.result returns a json containing the details of a single product (you can check the response of the example here). The actual on-demand price is buried somewhere inside this json, but I don't know how can I get it (image generated with http://jsonviewer.stack.hu/):
I know I might be able solve this by using an external data source and piping the output of an aws cli call to something like jq, e.g:
aws pricing get-products --filters "Type=TERM_MATCH,Field=sku,Value=8VCNEHQMSCQS4P39" --format-version aws_v1 --service-code AmazonEC2 | jq [........]
But I'd like to know if there is any way to accomplish what I'm trying to do with pure Terraform. Thanks in advance!
Unfortunately the aws_pricing_product data source docs don't expand on how it should be used effectively but the discussion in the pull request that added it adds some insight.
In Terraform 0.12 you should be able to use the jsondecode function to nicely get at what you want with the following given as an example in the linked pull request:
data "aws_pricing_product" "example" {
service_code = "AmazonRedshift"
filters = [
{
field = "instanceType"
value = "ds1.xlarge"
},
{
field = "location"
value = "US East (N. Virginia)"
},
]
}
# Potential Terraform 0.12 syntax - may change during implementation
# Also, not sure about the exact attribute reference architecture myself :)
output "example" {
values = jsondecode(data.json_query.example.value).terms.OnDemand.*.priceDimensions.*.pricePerUnit.USD
}
If you are stuck on Terraform <0.12 you might struggle to do this natively in Terraform other than the external data source approach you've already suggested.
#cfelipe put that ${jsondecode(data.aws_pricing_product.m4_large_price.value).terms.OnDemand.*.priceDimensions.*.pricePerUnit.USD}" in a Locals

POSTMAN - Save a property value from a JSON response

I am new to both JSON and Postman(as of yesterday).
I'm trying to do something very simple, I've created a GET request which pulls in a list of forms in a JSON response. I want to take this response and get the first "id" token and place it in a variable.
I am using a global variable but would like to use a collection variable if possible. Either way here is what I am doing.
I've tried several things, most recently this:
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("id", jsonData.args.id);
As well as this:
pm.test("GetId", function () {
var jsonData = pm.response.json();
pm.globals.set("id", jsonData.id);
});
Response code looks like this:
{
"forms":[
{
"id":"3197239",
"created":"2018-09-18 11:37:39",
"db":"1",
"deleted":"0",
"folder":"151801",
"language":"en",
"name":"Contact Us",
"num_columns":"2",
"submissions":"0",
"submissions_unread":"0",
"updated":"2018-09-18 12:02:13",
"viewkey":"xxxxxx",
"views":"1",
"submissions_today":0,
"url":"https://xxx",
"data_url":"",
"summary_url":"",
"rss_url":"",
"encrypted":false,
"thumbnail_url":null,
"submit_button_title":"Submit Form",
"inactive":false,
"timezone":"US/Eastern",
"permissions":150
},
{
"id":"3197245",
"created":"2018-09-18 11:42:02",
"db":"1",
"deleted":"0",
"folder":"151801",
"language":"en",
"name":"Football Draft",
"num_columns":"1",
"submissions":"0",
"submissions_unread":"0",
"updated":"2018-09-18 12:11:54",
"viewkey":"xxxxxx",
"views":"1",
"submissions_today":0,
"url":"https://xxxxxxxxx",
"data_url":"",
"summary_url":"",
"rss_url":"",
"encrypted":false,
"thumbnail_url":null,
"submit_button_title":"Submit Form",
"inactive":false,
"timezone":"US/Eastern",
"permissions":150
}
]
}
This would get the first id:
pm.globals.set('firstId', _.first(pm.response.json().forms).id)
That would get the first in the array each time so it would set a different variable it that response changed.
The test that you created was nearly there but the reference needed to go down a level into the forms array:
pm.test("GetId", function () {
var jsonData = pm.response.json()
pm.expect(jsonData.forms[0].id).to.equal("3197239")
pm.globals.set("id", jsonData.forms[0].id)
})
The [0]is referencing the first id in the first object within the array. For example [1] would get the second one and so on.
You currently cannot set a collection level variable using the pm.* API - These can only be added manually and referenced using the pm.variables.get('var_name') syntax.
Edit:
In the new versions of the desktop app you can set variables at the Collection level using pm.collectionVariables.set().
Based on the name or any other attribute if you want to set the id as a global variable then this is the way.
for(var i=0; i<jsonData.forms.length; i++)
{
if (jsonData.forms[i].name==="Contact Us")
{
pm.environment.set("id", jsonData.forms[i].id);
}
}

REST API status as integer or as string?

Me and my colleague are working on REST API. We've been arguing quite a lot whether status of a resource/item should be a string or an integer---we both need to read, understand and modify this resource (using separate applications). As this is a very general subject, google did not help to settle this argument. I wonder what is your experience and which way is better.
For example, let's say we have Job resource, which is accesible through URI http://example.com/api/jobs/someid and it has the following JSON representation which is stored in NoSQL DB:
JOB A:
{
"id": "someid",
"name": "somename",
"status": "finished" // or "created", "failed", "compile_error"
}
So my question is - maybe it should be more like following?
JOB B:
{
"id": "someid",
"name": "somename",
"status": 0 // or 1, 2, 3, ...
}
In both cases each of us would have to create a map, that we use to make sense of status in our application logic. But I myself am leaning towards first one, as it is far more readable... You can also easily mix up '0' (string) and 0 (number).
However, as the API is consumed by machines, readability is not that important. Using numbers also has some other advantages - it is widely accepted when working with applications in console and can be beneficial when you want to include arbitrary new failed statuses, say:
status == 50 - means you have problem with network component X,
status > 100 - means some multiple special cases.
When you have numbers, you don't need to make up all those string names for them. So which way is best in you opinion? Maybe we need multiple fields (this could make matters a bit confusing):
JOB C:
{
"id": "someid",
"name": "somename",
"status": 0, // or 1, 2, 3...
"error_type": "compile_error",
"error_message": "You coding skill has failed. Please go away"
}
Personally I would look at handling this situation with a combination of both approaches you have mentioned. I would store the statuses as integers within a database, but would create an enumeration or class of constants to map status names to numeric status values.
For example (in C#):
public enum StatusType
{
Created = 0,
Failed = 1,
Compile_Error = 2,
// Add any further statuses here.
}
You could then convert the numeric status stored in the database to an instance of this enumeration, and use this for decision making throughout your code.
For example (in C#):
StatusType status = (StatusType) storedStatus;
if(status == StatusType.Created)
{
// Status is created.
}
else
{
// Handle any other statuses here.
}
If you're being pedantic, you could also store these mappings in your DB.
For access via an API, you could go either way depending on your requirements. You could even return a result with both the status number and status text:
object YourObject
{
status_code = 0,
status = "Failed"
}
You could also create an API to retrieve the status name from a code. However returning both the status code and name in the API would be the best from a performance standpoint.

Getting and displaying JSON data fields using HTML and AngularJS

Im new to angularJS and web designing as a whole. Im trying to get a data field(or element) from a JSON. For example, this is what the JSON looks like
{
"Name":"Raymond Eugene Monce",
"Dateofbirth":"1924-0308T00:00:00Z",
"Ethnicity":"Caucasian",
"Languages":["{English}"],
},
and I'm trying to get the "Name" data field. This is what my .js file looks like,
var profile = angular.module('profile', ['ui.bootstrap','ngResource']);
profile.controller("profileController", ["$scope","$resource", function($scope, $resource) {
// get the user id
$scope.userid = sessionStorage["cerestiuserid"];
// json we get from server
$scope.apicall = sessionStorage["cerestihome"]; // NEED TO CHANGE API
// grabs the user we want
$scope.userResource = $resource($scope.apicall + "/api/userprofile/",
{Userid:21},
{'get':{method: 'POST'}}
);
// fetch JSON
$scope.userResource.get(function(result) {
// get the name field
$scope.name = result;
sessionStorage["name"] = JSON.stringify(result);
});
and my .html file,
<div ng-controller = "profileController" style="float:left">
<!-- profile pic -->
<div class="pull-left">
<div class="container-fluid">
<div class="profile">
<div class="row">
<div class="center-block">
<div class="profilePic">
<img ng-src="{{profilePic()}}" class="img-responsive">
<!-- name field -->
<label class="caption">
<h4>{{name.name}}</h4>
</label>
</div>
Again, Im not having problems with the Database or API calls. I just want to know how I can get and display the name field of the JSON. Thanks.
strelok2010's comment above should work although that depends on if your result really looks like the one defined at the top of your question.
Your result seems to be a normal javascript object not JSON. (yeah they are different, and that confused me when I learned it.) I assume that because you stringify the result from a javascript object into JSON. Therefore if that is working right your result is either a javascript object or an array of javascript objects. I'm assuming an array. You might want to check though.
I noticed your earlier post had a related problem.
In that one you were asking to access a property of an object that was in an array. In that case it was result as well. Here was the answer from your previous question
var result = [{"name": "Jason"
"date of birth": "february 23, 2985"
....
}];
var firstResultsName = result[0].name;
There are two things I am unsure of due to the inconsistency between this and your last question.
First your name property in your results object is spelled with a capital N here as opposed to a lower case n in your last question.
Keep in mind that capitilization matters in javascript.
Second your result in your last question was an array of objects and in this it seems to be just an object.
So depending on which one it is will determine your solution. So instead of writing every possible solution I'll show you how to determine the solution.
Remember we are dealing with a normal array of javascript objects. I'll try to go into detail so it's extra clear (sorry I heard you were new to web developement, I'm assuming JavaScript too.), but sorry if it's a little too detailed. I will also be breaking it into parts to go deeper into the array of objects that I'll use in my example, but traversing into the data structure can all be done in a single line as I will show.
You can only do actions on the 'outermost-form' (by the way 'outermost-form' is just a term I'll use for clarification it's not really a technical term.) and work your way into the collection (object/array/string)
As an example we have an array of people, with the array being the 'outermost-form'
var people = [
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
];
If we saw the value of people at this moment it not surprisingly be.
[
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
]
Start with the Array
Since it's an array as the 'outermost-form' we can get one of its values using an index. Just like any other array. Just for a bit of contrast I'll show you how what we are doing is similar to any other array by showing an example of an array by itself
// simple array example
var array = ["foo", "bar", "baz"];
array[0] // returns "foo"
// more simple array example, but less practical (it's more just for showing how javascript can work.)
["foo", "bar", "baz"][2] // returns "baz"
Back to our main example. Let's make a variable person and store our first person in the people array in that value.
var person = people[0];
Now if saw our person variable it would equal the following
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
}
You can see just like the normal array it grabs the first item in the array. You can see how we are slowly traversing into our people data structure. (that being an array of objects.)
Enter the Object
Okay so now we have the person object, but we want the name of that person so since we are dealing with an object we have to access its properties we can do this with either 'dot notation', e.g. <object>.<property>, or 'bracket notation' which can be done with either a variable or a string for the property name. e.g. <object>.["<property>"] or <object>.[<variable>]
So just as a side example I will show you what it normally takes to get the value of a property of an object just so you can compare and see there's no 'magic' going on. Keep in mind javascript is case-sensitive. Also javascript objects properties can go with or without surrounding quotes unlike JSON. One last thing having a space in the property name forces us to use quotes, and also forces us to access that property via bracket notation.
var result;
var obj = { foo: 1, Bar: 2, "foo bar": 3 };
var randomVarName = "Bar"; // notice the capital B in Bar is important since it was declared that way.
result = obj.foo; // result equals 1
result = obj[randomVarName]; // result equals 2
result = obj["foo bar"]; // result equals 3
Back again to our main train of thought. So we have traversed into our people array to find the person object now let's get their name.
var name = person.name;
The value of name would be.
"Bob"
You can do with that what you wish. You could have also used any of the previous ways to get an objects property including bracket notation.
Do Everything we just did in a Single Line
So to write that all in one line you would just write
people[0].name
Apply to your Question
So to apply to your question if your result looks like this
var result = [
{
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
];
Then you need this to get the name
result[0].name
If it's just this
var result = {
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
Then you just need
result.name
As asked in the comment if you want to get the date of birth property out of the object you need to use bracket notation to get the element out of an object. Bracket notation is one of the two object property accessors the other being dot notation. I covered both at the enter the object section. It can be used at anytime, but is usable in some cases that dot notation does not work.
An example and quote from MDN:
get = object[property_name];
object[property_name] = set;
property_name is a string. The string does not have to be a valid identifier; > it can have any value, e.g. "1foo", "!bar!", or even " " (a space).
So since certain character like spaces can't be used in dot notation bracket notation must be used in those special cases when those characters are present.
Below is the bracket notation of the date of birth.
result["date of birth"]
Like I said before it can be used anywhere, but generally dot notation is preferred for its brevity. So just to show that, we will show the name field being accessed using bracket notation:
result["name"]
One additional reason you may want to use bracket notation is for its ability to use variables like so.
var prop_name = "date of birth";
result[prop_name];
which actually if you understand the principle of that example the MDN example might make more sense.
If you have a question feel free to leave me a comment.

Iterating through couchbase keys without a view

In couchbase, I was wondering if there was a way - WITHOUT using a view - to iterate through database keys. The admin interface appears to do this, but maybe its doing something special. What I'd like to is make a call like this to retrieve an array of keys:
$result = $cb->get("KEY_ALBERT", "KEY_FRED");
having the result be an array [KEY_ALEX, KEY_BOB, KEY_DOGBERT]
Again, I don't want to use a view unless there's no alternative. Doesn't look like its possible, but since the "view documents" in the admin appears to do this, I thought i'd double-check. I'm using the php interface if that matters.
Based on your comments, the only way is to create a simple view that emit only the id as par of the key:
function(doc, meta) {
emit( meta.id );
}
With this view you will be able to create query with the various options you need :
- pagination, range, ...
Note: you talk about the Administration Console, the console use an "internal view" that is similar to what I have written above (but not optimized)
I don't know about how couchbase admin works, but there are two options. First option is to store your docs as linked list, one doc have property (key) that points to another doc.
docs = [
{
id: "doc_C",
data: "somedata",
prev: "doc_B",
next: "doc_D"
},
{
id: "doc_D",
data: "somedata",
prev: "doc_C",
next: "doc_E"
}
]
The second approach is to use sequential id. You should have one doc that contain sequence and increment it on each add. It would be something like this:
docs = [
{
id: "doc_1",
data: "somedata"
},
{
id: "doc_2",
data: "somedata"
}
...
]
In this way you can do "range requests". To do this you form array of keys on server side:
[doc_1, doc_2 .... doc_N]and execute multiget query. Here is also a link to another example
The couchbase PHP sdk does support multiget requests. For a list of keys it will return an array of documents.
getMulti(array $ids, array $cas, int $flags) : array
http://www.couchbase.com/autodocs/couchbase-php-client-1.1.5/classes/Couchbase.html#method_getMulti