URL encode Postman variable? - postman

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.

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]

Postman multiple api calls using the values from response body

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}}

Postman API -how to pass environment variable to another request jason body

I have create global variable. Set it as Test as env variaable corresponding quote id were stored in the CreateGLVar
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);});
var jsonData = pm.response.json();
pm.environment.set("CreateGLVar",jsonData.result.quoteID);
script for storing the value in Env variable
May i know how i can use value which is stored in the CreateGLVar for the below script. how i can the quote id from first request from global variable and insert dynamically in the second request( shown below) .
get quote id
enter image description here
Postman uses double curly braces to insert variables, which can also be used in raw request bodies.
In your specific case you can use:
"quoteID": "{{quoteIdVariable}}"
I am using the Postman Chrome extension Version 5.3.1, and this works for me.
Edit: Now that the Chrome extension has been depricated, this still works with the Postman Desktop app
Thanks Aaron.
I got the success when i used the "quoteID": "{{quoteIdVariable}}" in my bind API.my 2 API are working fine when i executed individually.
But I got issue when i executed API's as collection( Quote and Bind API). What i missing here if i executed as collection.
Failed

How can I let Analytics know my query is not finish before a utm code?

I'm trying to use a utm for a query on my page but sadly the url is like this:
comprar/es/torres/busqueda?searchTerm=103005+103004+125043+125042
The question mark inside prevents the use of the utm to track it,
¿Is there an equivalent to the backslash \ of RegEx that allow me to state that the first ? is still part of the query url string?
Thanks
the anwser to this is to set the utm as an extra parameter after the variables of the site
If this is the original URL:
mydomain.com/a/busqueda?searchTerm=103005+103004+125043+125042
You have to set it like this:
mydomain.com/a/busqueda?searchTerm=103005+103004+125043+125042&utm_source=sample&utm_medium=display&utm_campaign=test
Verify if work: comprar%2Fes%2Ftorres%2Fbusqueda%3FsearchTerm%3D103005%2B103004%2B125043%2B125042
You can use "Campaign URL Builder", site: https://ga-dev-tools.appspot.com/campaign-url-builder/

Cookie to log in with Jsoup?

For a project I'm trying to get data from a website only acessible when you're logged in from the site Goodreads.com. I'm new to Jsoup, since I'm using it only for this particular project. Getting the relevant data from the website is not a problem, but I can't seem to get to the particular page I need. The page I'm trying to acces is viewable only when logged in, when not logged in it rederects to the log-in page.
I've looked through the answers here, but the answers given so far have not helped.
What I have now:
String url = "http://www.goodreads.com/friend/user/7493379-judith";
Connection.Response res = Jsoup.connect("http://www.goodreads.com/user/sign_in")
.data("email", "MYEMAIL", "user_password", "MYPASSWORD")
.method(Connection.Method.POST)
.execute();
Document doc2 = res.parse();
String sessionId = res.cookie("_session_id");
Document doc = Jsoup.connect(url)
.cookie("_session_id", sessionId)
.get();
I got this far with help of the answers here, but it doesn't work, I'm still only getting the data from the log-in page it rederects to.
I have several questions:
Most importantly of course; How can I make it work?
The given answers here heve used method.(Method.POST) instead of method.(Connection.Method.POST) . When I use the first one however, I get an error that Method cannot be resolved. Anyone know why this is?
The examples I've seen have used "username" and "password" in .data() . What exactly do these refer to? I've now used the name of the input box. Is it the name, the type, the id, what exactly? Since Goodreads does not refer to the log in as the username, but as the e-mail, I assume I have to change them. (username & password doesn't work either)
Examples also use http://example.com/login.php as example url. Goodreads doesn't have a /login.php page though. Am I correct to assume I have to use the url with the log-in screen?
_session_id is the name of the relevant cookie on Goodreads.
I'd be very grateful if anyone can point me in the right direction!
See carefully what data is posted on login:
user[email]:email#email
remember_me:on
user[password]:plain_pasword
n:667387
So your post must execute exact same keys.
2.Make sure, you make right import: import org.jsoup.Connection.Method;
but Connection.Method.POST is still good.
3.See p1
4.Yes, you are correct
5.what is the question?
Goodreads requires two things when logging in: first, that you have a session ID stored in a cookie, and second, that you have a random generated number. You can get these when first visiting the login page without logging in: it will set a cookie with a session ID, and the form will contain a hidden input form (i.e. ) with the name "n" and value a number. Save these and pass them along as respectively a cookie and a form value when logging in.
Some remarks about the way I found this out:
The first thing you need to realise is that you're trying to recreate the exact same requests your browser does with Jsoup. So, in order to check whether what you have right now will work, you can try to recreate the exact same situation with your browser.
To recreate your code, I went to the login page, then I deleted all my Goodreads cookies (as you don't send along any cookies when you send the login request as well), and attempted to sign in with only passing the username and password form values. It gave an error that my session had timd out. When I first loaded the login page and then deleted all cookies except the session ID and did not remove the "n" form value, I could log in successfully. Therefore, you want to make a general GET request to the sign in page first, retrieve the session ID cookie you get there and the hidden form value, and pass it along with the POST request.
It could be that the API changed or that there just are several ways. Using Connection.Method.POST will do fine, in any case.
Yes, they refer to the names of the input boxes. This should be id, however, since name was used in the past and not all versions of all browsers supported passing the ids as data, most websites are just adding both. Either should be fine.
If you look at the source code of the sign in form, you can see that the "method" attribute of the form element is indeed the sign in page itself, so that's where it sends the request to.
PS. As a general tip, you can use the Firefox extension "Tamper Data" to remove form data or even cookies (though there are easier extensions for that).
You can log in with this code:
public static void main(String[] args) throws Exception {
Connection.Response execute = Jsoup
.connect("https://www.goodreads.com/")
.method(Connection.Method.GET).execute();
Element sign_in = execute.parse().getElementById("sign_in");
String authenticityToken = sign_in.select("input[name=authenticity_token]").first().val();
String n = sign_in.select("input[name=n]").first().val();
Document document = Jsoup.connect("https://www.goodreads.com/user/sign_in")
.data("cookieexists", "✓")
.data("authenticity_token", authenticityToken)
.data("user[email]", "user#email.com")
.data("user[password]", "password")
.data("remember_me", "on")
.data("n", n)
.cookies(execute.cookies())
.post();
}