postmanlabs / postman-app-support

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.
https://www.postman.com
5.84k stars 839 forks source link

[REQ] Reference other request on pre-request script #4193

Open stramel opened 6 years ago

stramel commented 6 years ago

It would be nice to be able to reference a pre-built login request from another request's pre-request.

harryi3t commented 6 years ago

Can you explain a bit more about what you mean by pre-built login request?

If you meant Sharing javascript functions/variables across scripts, then that should be done by serializing them and storing in some variable (env, global or *local) and then de-serializing then by using eval

Collection script

function commonFunction () {
  ...
}
pm.variables.set('commonFunction', commonFunction.toString())

Request script

eval(pm.variables.get('commonFunction'))
commonFunction()
stramel commented 6 years ago

In my collections of API requests I have already built a login request. I want to use that login request in my pre-request script. I don't want to have to redefine it and maintain it in more than one place.

harryi3t commented 6 years ago

From pre-request script, sending a saved request (one that is already in your collection) is not supported.

pm.sendNextRequest can be used to go from one request to another. If any request needs that loginRequest to be sent before, then put pm.sendNextRequest in the request before it.

As an example, let's say we have a collection with 5 requests out of which 2 requests (r2 & r4) needs a special request to be run before (loginRequest).

Request Name test-script
r1 pm.setNextRequest('loginRequest')
pm.variables.set('goto', 'r2')
r2*
r3 pm.setNextRequest('loginRequest')
pm.variables.set('goto', 'r4')
r4*
r5 pm.setNextRequest(null)
loginRequest let goto = pm.variables.get('goto')
pm.setNextRequest(goto)

If you follow this, the order of execution will be

START -> r1 -> loginRequest -> r2 -> r3 ->  loginRequest -> r4 -> r5 -> STOP

If this does not help, please let me know more about your use-case, so that I can suggest some workaround.

stramel commented 6 years ago

This problem is exactly what everyone was wanting solved when we requested PRE-request scripts.

It is useless to have every single request appear as though it is Login and then in the tests have the actual request sent.

chrisheil commented 6 years ago

+1 I am in the same situation. I would love to be able to reference existing requests in the same collection.

Maybe add an optional meta field on each request called "reference key", and anywhere that you need to call that request you could do something like this:

pm.sendPreRequest({{myLoginRequest}})

It would allow your saved login request to remain loosely coupled. You could update the request without needing to touch any other tests that depend on it.

cmonroeEIS commented 6 years ago
ykhodos commented 6 years ago

+1 Need ability to call a Postman request from a Pre-request Script, for example to initialize variables or set up the system before the test execution.

jayarjo commented 6 years ago

@harryi3t, In our setup every single request requires preliminary authorisation. At the moment we manually run auth request, that populates global variable and then other requests become functional. Would have been great if request itself invoked a saved auth request (if access token wasn't defined already) and then used an obtained token in authorisation header.

Turning each and every request into a separate collection feels a bit clunky?

rdemarco08 commented 6 years ago

I am glad to see there is activity on this subject :)

I have a similar scenario. Our checkout request is dependent on current available inventory. It would be nice to queue up available inventory in the pre-request of the Checkout call. Right now I am aware this can be done with the pm.sendRequest and type out the HTTP request. The workflow would be much more efficient if I could just reference an existing Availability request from the collection.

sebcharrot commented 6 years ago

+1

ggutenberg commented 6 years ago

Not an ideal solution, but I have a workaround.

In the request you want to reference, add the following to the Tests script:

console.log(JSON.stringify(pm.request));

Open the console (View > Show Postman Console) and send your request. Copy the JSON from the console verbatim. In the dependent request, simply add a pm.sendRequest() and paste your JSON object as its argument. Example using the Postman Echo GET Request (prettified JSON to avoid endless horizontal scrolling):

pm.sendRequest({
  "description": {
    "content": "The HTTP `GET` request method is meant to retrieve data from a server. The data\nis identified by a unique URI (Uniform Resource Identifier). \n\nA `GET` request can pass parameters to the server using \"Query String \nParameters\". For example, in the following request,\n\n> http://example.com/hi/there?hand=wave\n\nThe parameter \"hand\" has the value \"wave\".\n\nThis endpoint echoes the HTTP headers, request parameters and the complete\nURI requested.",
    "type": "text/plain"
  },
  "url": {
    "protocol": "https",
    "path": [
      "get"
    ],
    "host": [
      "postman-echo",
      "com"
    ],
    "query": [
      {
        "key": "foo1",
        "value": "bar1"
      },
      {
        "key": "foo2",
        "value": "bar2"
      }
    ],
    "variable": []
  },
  "header": [
    {
      "key": "cache-control",
      "value": "no-cache"
    },
    {
      "key": "Postman-Token",
      "value": "1069648b-fcab-4a67-bf0a-9004719c4c79"
    },
    {
      "key": "User-Agent",
      "value": "PostmanRuntime/7.2.0"
    },
    {
      "key": "Accept",
      "value": "*/*"
    },
    {
      "key": "Host",
      "value": "postman-echo.com"
    },
    {
      "key": "cookie",
      "value": "sails.sid=s%3AmMiIAoQi17Kylyh__5buLn6bMbzFQ9gA.XrOJ96IZ%2BEjJbeVoa8RAPP5ePiWcFuWOHuaXmFBYLb8"
    },
    {
      "key": "accept-encoding",
      "value": "gzip, deflate"
    }
  ],
  "method": "GET",
  "body": {
    "mode": "raw",
    "raw": ""
  }
});

If you're using variables of any sort, you'll have to replace the values in the JSON with something like pm.variables.get('my_variable').

HTH!

omnipotentkrishna commented 6 years ago

https://github.com/postmanlabs/postman-app-support/issues/4193#issuecomment-417131032 Hi All, I am new to Github. I have question. As above mentioned I have used pre-request script where I have formed request and sent, however i am getting response but my question is how we can store or use response which we are getting from pre-request-Script? I have tried pm.response.json() but as per API doc this methods can be only used in Test methods. Could you anyone please tell me how to save or get response and create it? For me I have to send request in pre-request-script, I will get response, from that response I have to create new JSON string which I want to use request body for another request.

Thanks, Krishna

jasonycw commented 6 years ago

+1 Is there any news of how to do that?

Was preparing some API collections for testing create, edit and delete APIs It will be great to be able to call the create/delete API before the edit one and reusing another saved API will be helpful for initiate those global variables like IDs.

This can make the integration tests with Runner and newman to run much more smoothly.

pomeh commented 5 years ago

This issue looks similar to #882 and #4845. Maybe you'll find some solutions in those threads.

humbienri commented 5 years ago

@ggutenberg thank you for your idea/suggestion! It does seem quite hacky but I think it sorta works. However, I think it works because the cookie is already set in the Headers? If my independent request is an authentication/login request and I need to pass in a username and password in the raw body and those values are actual hard-coded values and not variables as you suggested, then it does work!

However, if I remove the cookie part and try to variablelize the username and password then I cannot get it to work. Were you able to actually use varaibles in your efforts or was that just a suggestion?

Thank you!

guanyingjie commented 4 years ago

Do we solve this problem now? I meet the same question

hedrickbt commented 4 years ago

I have the same issue. I have a login-request that sets a token environment variable. Then each of my other requests uses that environment variable. It would make sense for the other requests to call my login-request first and then token would be set. This supports the DRY principle too.

The workaround of copying the console version of my login-request into each request would work. But, with more than 50 requests in my collection, I would not look forward to the day I needed to change how the login-request worked.

arlemi commented 4 years ago

Hey everyone, we'll be using this issue to consolidate the feedback we've got around that feature request (#697, #4845, #4024).

Existing feedback

Here's the different use-cases for which that feature would be useful:

Workarounds

You can use postman.setNextRequest(); along with the Collection Runner to build a workflow with different requests, see Building workflows. You can also use pre-request scripts (at the request or collection level) to send an auth request and save the result in environment variables, here's an example on how to get a bearer token from Auth0 and save it for reuse.

Next steps

If you have a use case that isn't mentioned above please add it as a reply to this post. Otherwise please make use of the 👍 reaction on the first post to show your support for that feature request, but please please avoid replying only with an emoji or a +1 since this clutters the issue and sends unwanted notifications to all participants. 🙏

kbradl16 commented 4 years ago

Some more information would be great since we’ve all been waiting for this feature for years now!

Does this mean you will be starting to work on this issue or are you only “consolidating” it?

How is this being prioritized?

When can we expect this to drop?

Are you adding all the use cases up front or incrementally?

arlemi commented 4 years ago

@kbradl16 We're consolidating feedback for now. While we haven't implemented this particular feature, we've been working on other ones that have made it easier to workaround this one (see workarounds in my previous post).

We'll be giving all status updates here.

lflucasferreira commented 4 years ago

I would really appreciate this feature. Today I needed it. So, I am trying to make one working around.

AlexLombry commented 4 years ago

I don't understand really why in Postman we cannot send via Pre Request Script a Postman request without searching a kind of Hack to do it.

It seems that it's a feature a lot of people want.

In my case i need to retrieve a Token that change on each request. I just want to use something like that :

pm.sendRequest({
    url: PostmanRequestUUID, // id of a already saved request: "Get Token For User"
}, function (err, res) {
    pm.environment.set("userToken", res.json().token);
});

Every call i have need to be logged in like that.

yashraja commented 4 years ago

I really really wanted this :-) This would help me in lot of ways to simplify problems.

nahu90 commented 4 years ago

Please we need this!

zeeshanyshaikh commented 4 years ago

👍 Yes this is much needed.

My case is i need to get token before every call. I am using oauth2 authentication which requires 2 call as usual. One for getting the grant code and other for getting the actual token and refresh token.

So i have created a folder named "Auth" and added 3 requests (1 extra for refreshing the token). I tried using built in method (Get Access Token Dialog box) but in that case am not getting the whole json in the header, getting only access token.

Along with this request, i would like to have one more request. If this feature is available and can be added to collection pre-scripts then (for my case) Auth folder should be skipped, since i don't want to run those pre-script for my "Auth" requests again. Sounds complex :) but let me know if there is any workaround for my 2nd request (feature request to be specific)

Totti10as commented 4 years ago

Feature must!

AlexLombry commented 4 years ago

For instance it's a feature already working with Paw : https://paw.cloud/docs/auth/jwt I use this now

KarFan-FS commented 4 years ago

I also want this feature

marcelmrottmann commented 4 years ago

I also need this feature

KasperLK commented 4 years ago

Insomnia's request chaining is very easy to setup and even reuse in variables.

ShaneFromFargo commented 4 years ago

Adding my +1 here as well. This would've been very useful for me today.

lipedias commented 4 years ago

+1

VincentWinckelmans commented 4 years ago

+1

Peter-Schorn commented 4 years ago

+1

PPatel0212 commented 4 years ago

This feature would be useful

molteninjabob commented 4 years ago

It seems that all of the scenario requests could really be resolved by creating a script repository at the folder, collection, and/or global level. Define a function at any of these levels and allow that function to be called at the level defined and any level below that. It's a pretty simple concept and one that is regularly used as a basic coding best practice. Such scripts would also have regular access through the pm object to any global, environment or collection/script/request level variables that are defined. Not sure why this has taken years to gain traction.

CriggerMarg commented 3 years ago

Please do it, we need it badly

srbangre commented 3 years ago

Following. Have been wanting this feature since 2 years now :(

tony-li-avepoint commented 3 years ago

It's been five years, for five years...Do you know how have I been doing for five years without this feature!!! #697

elazar commented 3 years ago

It's been five years, for five years...Do you know how have I been doing for five years without this feature!!! #697

Duplicating defined requests a lot because you couldn't just reference them?

mwmcode commented 3 years ago

☝️ we have a winner 🏆

tony-li-avepoint commented 3 years ago

It's been five years, for five years...Do you know how have I been doing for five years without this feature!!! #697

Duplicating defined requests a lot because you couldn't just reference them?

OK, I see, just a kidding, don't mind.

lflucasferreira commented 3 years ago

I believe I'm gonna die and this feature will never be implemented. It's already in Insomnia but Postman. Nevertheless, I'll not leave Postman behind.

molteninjabob commented 3 years ago

@shamasis @a85 @preethammavin - Why does this feature request continue to get ignored?

matvi commented 3 years ago

Adding my +1

jameslgarrett commented 3 years ago

I would love to see this feature as well!

KittyGarrison commented 3 years ago

We still want this 🥺🙏

pyashish commented 3 years ago

This is the only think blocking our team using newman!

4nif commented 3 years ago

any good news on this feature request?

GabrielBarberini commented 3 years ago

5079gv