Postman multiple api calls using the values from response body - postman

I am a new postman user. I attached a screenshot to show you my parameters. I get a new "nextpagetoken" every time I call this api. The listid and activitytypeid are not changing. What I want to do is finding a way to rerun this call automatically until there is no "nextpagetoken" in the response body. I also want to save the response of each call, separately if possible.
I've found a few solutions but given that I am a new user, I didn't fully understand them + none of them explains how to save the response automatically.
Any help will be appreciated!

You do not include a lot of details in your question, so I am going to use a generic example for this answer.
Let's say you want to call https://mysite/token with a Post call, from which you get a response using json with a token you need to reuse.
In your collection, create a new request. Select POST and write the url https://mysite/token.
Go into the tests tab. Assuming that the output of the call to your url is a json structure like this
{
"jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}
You will need to write a script to capture the token like this:
var data = pm.response.json();
var accessToken = data.jwt;
pm.globals.set("token", accessToken);
now you can use it in your next request. Either in the url, if the next page is a get (e.g. http://mysite/page?token={{token}}) or anywhere else, like the parameters.
Just enclose it in double curly brackets. {{token}}
You will also be able to se it in your globals.

You can create an environment which, if selected, is accessible globally. Then you would call that variable by accessing it {{likethis}}

Related

How to post an object in postman without FromBody?

Let's say my controller is taking an object parameter without [FromBody], how do I post the data using Postman? I tried this way but it doesn't reach the endpoint.
I think in this case, since you're not using [fromBody] your object should be in the URL and not in the Request Body.
in Postman, this can be done using the Query Params as the screenshot shows.
Yet, I don't think you could pass an object in the query params like that. I think you should instead turn it into a query string like this format
"User=abc&Pass=abc"
Multiple ways to achieve this can be found here
If your controller is taking an object parameter without [FromBody] then you must send the data as URL parameter:
POST http://localhost:44364/login?object={"User":"abc","Pass":"abc"}
Note: replace "object" by the name of the parameter in your controller. Also you have to know that Postman should converts special characters { " : , to %XX format and you have to manage that in your service.
If you want to send it in the body, then include [FromBody]

URL encode Postman variable?

I use Postman for REST API testing and parametrize tests with global variables.
I should put a phone number into GET request: /path/get?phone={{phone}} but leading + sign in the phone number is interpreted as a space.
What is the syntax to URL encode global variables in Postman? Is it possible to run JS encodeURIComponent() on variable in URL?
I am late but still worth it:
Just highlight and right click the part of url you want to encode. Select encodeURIComponent
That's it.
Use the Pre-request scripts (it's next to body) for this:
var encoded = encodeURIComponent({{phone number}});
or
var encoded = encodeURIComponent(pm.environment.get("phone number"));
and to proceed, use:
pm.environment.set("encoded phone number", encoded);
And set your URL to /path/get?phone={{encoded phone number}}
Just a shortcut to Mohhamad Hasham' answer.
You can encode and decode direct in the Params Value field:
The trick is to get your environment variable in the pre-request script and then set it after encoding it
var encoded = encodeURIComponent(pm.environment.get("phone"));
pm.environment.set("encoded phone number", encoded);
This will work as well:
var encoded = encodeURIComponent(pm.request.url.query.get("phone"));
pm.request.url.query.remove("phone");
pm.request.url.query.insert("phone", encoded);
I came across this question looking for an answer to a similar question. For me, the variable was a JSON object. The endpoint I needed to hit was expecting an object list as a query parameter and I have no way to change that to be the request body.
As much as some of the answers helped, I ended up coming up with a combined solution. Also, some of the code given in other answers is outdated as Postman has updated their API over the years, so this uses methods that work on 7.22.1.
pm.environment.set("basicJSON", '[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]')
var encoded = encodedURIComponent(pm.environment.get("basicJSON"))
pm.environment.set("encodedJSON", encoded)
This solution requires that both basicJSON and encodedJSON exist as environment variables. But what was important for me was the ease of editing the object. I didn't want to have to decode/encode constantly to change values, and I didn't want to have to open the environment variables dialogue. Also, it's important to note the single-quotes around the object. Excluding them or using double-quotes would cause Postman to send something like "[object Object]" which is useless to an endpoint expecting actual JSON.
I had similar problem with braces { and } in query parameter.
By turning off the following setting it started working for me.
For the postman version 9.28.4 ==>
You can use 2 methods:
By selecting the part of the url in url bar -> right click -> EncodeURLComponent. (screenshot attached)
You can also use "pre-request script" tab of postman and write the script for the variable manually. (screenshot attached)
The problem with right-click => Encode URI Component is that it destroys the raw value of that parameter. You can use the following pre-request script to overcome this (which also works for cases where you have disabled that param):
// queryParam is of type https://www.postmanlabs.com/postman-collection/QueryParam.html
if ((queryParam = pm.request.url.query.one("name_of_your_query_param")) !== undefined
&& queryParam.disabled !== true) {
queryParam.value = encodeURIComponent(queryParam.value);
}
Click the Params button to open the data editor for URL parameters. When you add key-value pairs, Postman combines everything in the query string above. If your URL already has parameters - for example, if you are pasting a URL from some other source. Postman splits the URL into pairs automatically.
https://www.getpostman.com/docs/v6/postman/sending_api_requests/requests
POSTMAN's documentation on building requests in the section "sending parameters" is helpful here. You can encode path data by simply encoding the URL with a colon, listing the key name of the encoded element, and then a new section will appear below the query parameters allowing you to customize values and add a description, just as we do with query params. Here's an example of encoding the URL for a GET request:
https://somesite-api-endpoint/:record/get
And here's what the display looks like after you add path data. Any value you add in the path variables section will automagically update the URL with your data.

Postman - can I save some of the cookie information returned in a variable?

My first step is always the same - log in. When I log in I need to get four pieces of information from the headers. I then need to use those four cookies/values/whatever for subsequent actions (POST, PUT, GET, etc...)
Is there a way to save those four pieces of information from the headers into variables so that I can use them in my next query? Since my session seems to time out after like 3 minutes all the copy and pasting is driving me mad.
I found this for the response body:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);
How can I do something like that but for information returned in the header?
if this is still an issue for you, you may have a look at this: https://www.getpostman.com/docs/postman/scripts/postman_sandbox
In paragraph "Request/response related properties" you have information on how to extract data from headers (request or response) and in the paragraph above, how to get data from cookies ...
hope this helps
Alexandre

Passing a token/value into an application express custom authentication scheme

I am trying to pass an encrypted token from an external application into Application Express. I want to read and work with this token in a custom authentication scheme as a way to authenticate the user into the application.
What is the best way to do this? At first, I was trying to just append the token onto the URL, eg:
/pls/apex/f?p=999:1&Token=XXXXXXXX
But then Apex returns a 404.
So then, I was trying to use the Application Express session values to send in the token, creating a URL like this:
f?p=999:1:::::TOKEN:XXXXXXXX
And then my sentry function I would do something like:
v_token := V('TOKEN')
To get it. However, this isn't working either, and I think's because the session isn't established yet when the sentry function executes? And is it even possible to do it this way? (Since there would be no item with this name, and no page yet to create it on...)
Is there a better approach to doing what I'm trying to do? If I had this added as a HTTP Header upstream, can I read that somehow in the sentry function? Maybe with owa_util.get_cgi_env? Does that work to read HTTP Headers from the request?
Thank you
If anyone else runs into something like this - I figured out a workaround.
Just put the token in the "value" session variables section of the URL, like so
f?p=999:1::::::XXXXXXXX
Then in the "sentry function" I can get the entire query string like this:
v_query_str := owa_util.get_cgi_env('QUERY_STRING');
And then I can split v_query_str by : and get the 8th token, which is what I need.
I found some examples using apex_util.string_to_table to split the string, which works nicely.

How to filter a Backbone collection on the server

Is there a common pattern for using Backbone with a service that filters a collection on the server? I haven't been able to find anything in Google and Stack Overflow searches, which is surprising, given the number of Backbone apps in production.
Suppose I'm building a new front end for Stack Overflow using Backbone.
On the search screen, I need to pass the following information to the server and get back a page worth of results.
filter criteria
sort criteria
results per page
page number
Backbone doesn't seem to have much interest in offloading filtering to the server. It expects the server to return the entire list of questions and perform filtering on the client side.
I'm guessing that in order to make this work I need to subclass Collection and override the fetch method so that rather than always GETting data from the same RESTful URL, it passes the above parameters.
I don't want to reinvent the wheel. Am I missing a feature in Backbone that would make this process simpler or more compatible with existing components? Is there already a well-established pattern to solve this problem?
If you just want to pass GET parameters on a request, you should just be able to specify them in the fetch call itself.
collection.fetch( {
data: {
sortDir: "ASC",
totalResults: 100
}
} );
The options passed into fetch should directly translate to a jQuery.ajax call, and a data property should automatically get parsed. Of course overriding the fetch method is fine too, especially if you want to standardize portions of the logic.
You're right, creating your own Collection is the way to go, as there are not standards about server pagination except OData.
Instead of overriding 'fetch', what I usually do in these cases is create a collection.url property as a function, an return the proper URL based on the collection state.
In order to do pagination, however, the server must return to you the total number of items so you can calculate how many pages based on X items per page. Nowadays some APIs are using things like HAL or HATEOAS, which are basically HTTP response headers. To get that information, I normally add a listener to the sync event, which is raised after any AJAX operation. If you need to notify external components (normally the view) of the number of available items/pages, use an event.
Simple example: your server returns X-ItemTotalCount in the response headers, and expects parameters page and items in the request querystring.
var PagedCollection = Backbone.Collection.extend({
initialize: function(models,options){
this.listenTo(this, "sync", this._parseHeaders);
this.currentPage = 0;
this.pageSize = 10;
this.itemCount = 0;
},
url: function() {
return this.baseUrl + "?page=" + this.currentPage + "&items=" + this.pageSize;
},
_parseHeaders: function(collection,response){
var totalItems = response.xhr.getResponseHeader("X-ItemTotalCount");
if(totalItems){
this.itemCount = parseInt(totalItems);
//trigger an event with arguments (collection, totalItems)
this.trigger("pages:itemcount", this, this.itemCount);
}
}
});
var PostCollection = PagedCollection.extend({
baseUrl: "/posts"
});
Notice we use another own property, baseUrl to simplify extending the PagedCollection. If you need to add your own initialize, call the parent's prototype one like this, or you won't parse the headers:
PagedCollection.protoype.initialize.apply(this,arguments)
You can even add fetchNext and fetchPrevious methods to the collection, where you simply modify this.currentPage and fetch. Remember to add {reset:true} as fetch options if you want to replace one page with the other instead of appending.
Now if your backend for the project is consistent, any resource that allows pagination on the server may be represented using one PagedCollection-based collection on the client, given the same parameters/responses are used.