Reusing requests and scripts

Number of APIs: 1

πŸ” Get Started Here

The aim of this collection is to demonstrate how a request or a script from a collection can be reused/referenced in a different collection.

This idea can also be extended to create a repository of scripts and reuse them across different collections.

NOTE: The only caveat with this approach is that you will have to make an extra API call to fetch that request/script.

πŸ”– How to use this template

  1. Add your [API Key] in the Variables tab of the collection. You can access your API key here.
  2. Add the following script as part of the pre-request or test script based on your use case.
eval(pm.variables.get("executeReferencedRequest"));
executeReferencedRequest({
    collectionUId: "<COLLECTION_UID>",
    requestUId: "<REQUEST_UID>", // can also use requestName instead
    apiKey: pm.variables.get("apiKey")
}, () => {
    eval(pm.variables.get("referencedPreRequestScript"));
    pm.request.update(pm.variables.get("referencedRequest"));
    eval(pm.variables.get("referencedTestScript"));
});

Here collectionUId is the UID of the collection from which you want to reference the request and requestUId is the UID of the request that you want to reuse/reference. These can be copied from the right sidebar by clicking on β“˜ of a collection or a request respectively.

executeReferencedRequest here will set three local variables which are:

  • referencedPreRequestScript - Contains the pre-request script of the referenced request.
  • referencedTestScript - Contains the test script of the referenced request.
  • referencedRequest - Contains the actual referenced request.

These can then be used accordingly in your request. This collection contains example for reuesing, request, pre-request script and test script.

ℹ️ Resources

Please refer to this Gist on Github

  1. Reuse a test script (Alternate Method) GET https://postman-echo.com/get