I'm new to using postman to create tests for a simple api. As part of this I want to create a post request, then use the generated id in subsequent Get, Put and Delete tests. Below is how I'm saving the id as a variable (have also saved it in the environment) and my API schema.
pm.test("Status code is 201", function () {
pm.response.to.have.status(201);
var jsonData = pm.response.json();
pm.environment.set('todo2', jsonData.id)
});
{
"id": "integer",
"name": "string",
"isComplete": boolean
},
But when I try to call my Get request for that generated id using {{todo2}} in my header it instead returns everything from my API rather than the specific api which I thought I had saved in the variable. Can anyone help point me in the right direction, not sure where I'm going wrong.
are you sure you json is valid?
{
"id": "integer",
"name": "string",
"isComplete": "boolean"
}
you need double quotes for boolean value, because this is a string there.
Solved the problem! I was updating my environmental variables and trying to call global variables, so I was getting an undefined.
Solved by changing my code to the below and making sure I had declared my variables via the global environment menu on the top right.
pm.test("Status code is 201", function () {
pm.response.to.have.status(201);
var jsonData = pm.response.json();
pm.globals.set('todo2', jsonData.id)
});
Related
I have been traversing through Stackoverflow and everywhere else on the web to try and find a solution to my issue..
I am working in Javascript and attempting to POST a small section of JSON to an endpoint in the API i know is working (I have completes the GET and POST manually in Postman)
Here is my issue..
I want dont really want to do the "GET" in my programme I just want to either reference the file or even just store it in a little variable.
So for example I have in my code:
var OauthUpload = {
"objects": [
{
"name": "api",
"serviceID": 16,
"properties": {}
}
],
"version": "integration",
"environment": "redshift"
}
Then I am trying to reference this in the JS function:
function ApiPostOauth (port) {
$.post(OauthUpload, "http://docker.dc.test.com:" + getActualPort(port) + "/rest/v1/oauth/import", runner);
}
But I am having no joy! I have seen a few different silutions but none seem to fit for me.
Basically I want a way to just:
Reference my own JSON as a variable and then insert tht so my function "ApiPostOauth" has that inserted before it runs?
Thanks guys
Steve
I have put together an example for your use. When executing this code, the server will return the same object it is sent. So the 'OauthUpload` object is sent as the request body and the server returns the exact same object. Note: if you don't see output in the output panel when running the sample I will need to restart the server (leave a comment). This is here to demonstrate:
[EDIT] - after re-reading your question, it appears you would like to pass the 'OauthUpload` object into the function. I've updated the example.
You have a mistake in your call to jQuery post() method. As shown in the comments, the first two arguments are reversed in the call to post().
Since you didn't pick up on that, I decided to provide an example using your code. Since I don't have your server, I stood up a server for this example. So the URL and port will be different, but the AJAX call will be the same.
Please pay close attention to the OauthUpload object. Notice the property names are no longer surrounded by ". I removed these quotes because they seemed to be causing you confusion about JavaScript objects and JSON strings (there is no such thing as a JSON Object regardless of what you read on the web - JSON is a string format).
Next, look at the differences between the call made to $.post() in my example and your code. You will see the URL comes first in that call.
let url = "//SimpleCORSEnabledServer--randycasburn.repl.co/rest/v1/oauth/import";
let OauthUpload = {
objects: [{
name: "api",
serviceID: 16,
properties: {}
}],
version: "integration",
environment: "redshift"
}
ApiPostOauth(OauthUpload);
function ApiPostOauth(data) {
$.post(url, data, runner)
}
function runner(data) {
document.querySelector('pre').textContent = JSON.stringify(data, null, 2);
}
<pre></pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm new to AngularJS so my mistake might be anywhere in my code and I can't find it. I'm using $HTTP GET method to retrieve data that's located in some server /page. After retrieving that data (which is JSON) I want to play with that string to retrieve the data properly, like name: number: and so on. But the thing is once I put that data into $scope.listOfCompanyUsers I can't touch it. If I try to $scope.listOfCompanyUsers.slice(..) or if I try any other string function on that object my entire webpage crashes. I "alert()"'d the $scope.listOfCompanyUsers and the result is:
<pre>[
{
"admin": true,
"id": 123,
"username": "someName",
"last_name": "someLastName",
"name": "John Doe"
}
]</pre><br>
What I wanted to do is remove the pre and br tags from that string so I have a pure JSON string that I could play with but again any function I try on $scope.listOfCompanyUsers crashes my site. What do I do? I tried var someOtherVariable = $scope.listOfCompanyUsers but that variable doesn't work later. I'm adding parts of my code because my mistake might be somewhere else.
Controller:
$http({
method: 'GET',
url: '/someURL'
}).then(function successCallback(response) {
$scope.listOfCompanyUsers = response.data;
},
function errorCallback(response) {
alert(response.status);
});
Later on the same controller:
.
.
$scope.someFunction = function () {
.
.
else {
alert("Maximum of 9 other passengers!");
alert($scope.listOfCompanyUsers);
// In this alert I could see the $scope.listOfCompanyUsers as mentioned above
}
};
My target right now is to have a var objectOfUsers = [{admin: true, id:123, username: "name", last_name: "test", name: "something"}, {next user.}, .] but because I can't touch the $scope.listOfCompanyUsers I'm stuck.
The problem is that the server is adding some extra tags to the response that shouldn't be in there:
<pre>[
{
"admin": true,
"id": 123,
"username": "someName",
"last_name": "someLastName",
"name": "John Doe"
}
]</pre><br>
Edit your server-side code, to remove: <pre> and </pre><br>.
Then the call will work.
Is your response a string? If your response has HTML tags, then that is not valid JS object format. It looks like you have a Javascript array with one object, enclosed by some HTML tags.
Therefore you won't be able to access anything within this using the object reference notation (.) until you treat it like a string and use String.prototype.replace and replace the tags, and then do a JSON.parse on the remaining string to convert it into an object
Very strange server response, so possible solutions are:
Change server response to standard JSON without unwanted <pre>
If You can not change response remove not wanted part of response using regular expression in JS. Working example how do that:
var response='<pre>[{"admin": true, "id": 123, "username": "someName","last_name": "someLastName", "name": "John Doe"}]</pre><br>';
var goodResponse=response.match(/>([^<]*)</)[1];//remove not wanted signs
var parsedGoodResonse=JSON.parse(goodResponse);
console.log(parsedGoodResonse);//here we have parse js array
In parsedGoodResonse You have object which can be "touched" so exactly what You need.
The problem with the extra tags is not on your code, it's on the server-side. You should check the code on the server and find the reason for those extra tags. They can't be there because they are making the response an invalid JSON.
I have an API in a Node.js which requires a JSON file, and on some requests maps in content from it. Simple enough, and works perfectly for the first request.
On subsequent requests one of the properties is left off. This is obviously a stripped down version of the code, but is all I'm doing to get the content.
Essentially my JSON looks like:
{"sections": {
"city": {
"title": "Seattle",
"info": "some info",
"tips": [ "tip 1", "tip 2" ]
}
}
}
and I require it:
var Content = require("content");
// some code
return req.status(200).json({ data: data, content: Content.sections.city });
The first request returns the whole content object. Every request after that returns only title and info, but not tips.
Edit -- I'm a dummy. In the //some code section, I work with the tips and eventually call delete on this version of the object. Apparently passing by reference still hasn't sunken in.
I've tested my REST service with success using Advanced Rest Client, where I'm sending a payload that looks like this:
{
"comments":"test comments",
"internal_verification_areas":[
{
"area_id":"1",
"selected":"1",
"notes":"notes1",
"status":"1"
},
{
"area_id":"2",
"selected":"0",
"notes":"notes2",
"status":"0"
}]
}
As mentioned my REST function executes with success.
I then moved to implement the whole thing on my web-interface and created the internal_verification_areas object as follows:
var verification_areas = {
internal_verification_areas: [
{
area_id:"1", // no need to quote variable names
selected:"1",
notes:"noter",
status:"1"
},
{
area_id:"2", // no need to quote variable names
selected:"1",
notes:"noter2",
status:"1"
}
]
};
The whole thing is then fed into my request like this (comments parameter is fetched from a textarea):
$.post("createInternalVerification.php",{comments: $('textarea#korrigeringer').val(),internal_verification_areas: verification_areas}
createInternalVerification.php will json encode the data and request the service.
The problem is, that i get an error saying: "Integrity constraint violation: 1048 Column 'area_id' cannot be null". I assume there is something wrong with my posted data, but i can't figure out what. From my POV my Advanced Rest Client payload looks similar to the payload i send from my web-interface.
EDIT:
I've noticed that the network tab (google chrome) shows some differences in my payload. I'm returning internal_verification_areas in my response to analyze the difference.
(MY WEB INTERFACE RECEIVES)
{"error":false,"message":"Intern efterprovning oprettet","test":{"internal_verification_areas":[{"area_id":"1","selected":"1","notes":"noter","status":"1"},{"area_id":"2","selected":"1","notes":"noter2","status":"1"},{"area_id":"3","selected":"1","notes":"noter3","status":"1"}]}}
(ADVANCED REST CLIENT RECEIVES)
{"error":false,"message":"Intern efterprovning oprettet","test":[{"area_id":"1","selected":"1","notes":"jAAAAAAA","status":"1","id":"4"},{"area_id":"2","selected":"0","notes":"NEEEEEJ","status":"0","id":"5"}]}
Guess I messed up my understanding of objects and arrays. Turns out my web-interface was sending and array with and object with arrays. Changing it (as shown after this post) fixed my mistake. I'm so sorry zerkms for wasting your precious time and causing an immense annoyance to your unicum skilled mind. I find it more and more frightening to post questions on StackOverflow with the presence of such skilled and godlike figures who constantly remind minions such as myself that Stackoverflow has become the very bedrock of arrogant developers.
var internal_verification_areas = [
{
area_id:"1", // no need to quote variable names
selected:"1",
notes:"noter",
status:"1"
},
{
area_id:"2", // no need to quote variable names
selected:"1",
notes:"noter2",
status:"1"
},
{
area_id:"3", // no need to quote variable names
selected:"1",
notes:"noter3",
status:"1"
}
];
i have a running program that will display my data from a server to the jqgrid. what i want now is to save data to the server. here's my code:
function Add(){
var datas = {
"ID": "xyz",
"operation": "Add",
"fields": ["code", "desc", "type"],
"values": [$('#code').val(), $('#desc').val(), $('#type').val() ]
}
$('#tblData1').setGridParam({
url:'myni.php?path=' + encodeURI('this/update') + '&json=' +(JSON.stringify(datas)),
datatype: Settings.ajaxDataType,
});
$('#tblData1').trigger('reloadGrid');
}
this codes returns an error message "Exception error: Server Error: Parameter 'operation' is not specified." i already set an operation and i don't know what went wrong. can somebody help me fix this? please.
i want to know how to add data to the server after clicking the button and display it in the jqgrid right away. Please...
The function Add set local variable datas which exist only inside of the Add function. Probably what you want is to return the value from the function and set to the variable existing in the scope of usage the setGridParam call.
The next problem is that you should encode JSON.stringify(datas) with respect of encodeURIComponent before inserting it as the part of URL. You can also use jQuery.param function instead:
url:'myni.php?' + $.param({path:'this/update', json:JSON.stringify(datas)})
If you use HTTP GET (mtype:'GET') for requests to the server I would recommend you better to use postData parameter of jqGrid which contain functions:
$("list").jqGrid({
url:'myni.php',
postData: {
path: 'this/update',
json: function() {
return JSON.stringify({
ID: "xyz",
operation: "Add",
fields: ["code", "desc", "type"],
values: [$('#code').val(), $('#desc').val(), $('#type').val()]
});
}
},
// other parameters
});
The properties of postData parameter will be added to the URL ('?' and '&' will be inserted if needed) in case of the usage of mtype:'GET' or to the body of the posted data in case of mtype:'POST'.
The advantage of the usage functions inside of postData is that the corresponding values (like the value of json parameter) will be calculated on every ajax request. If the user changes the sort order or chooses another page the ajax request to the server will be send. So in the case the postData properties must be determined and the current values from $('#code').val(), $('#desc').val() and $('#type').val() will be inserted in the request.
If the value of path parameter should not be static you can make it also as the function.
In case of usage postData which includes functions you code could be reduced to $('#tblData1').setGridParam({datatype: Settings.ajaxDataType}).trigger('reloadGrid').
More about the usage of functions inside of postData you can read here.