Using Variables in Packages

  • Using Variables in Package Library:
  • How does one access variables in the package library?: I have a JSON schema checker that I need to use in every API endpoint that I use. To do this in the post request scripts I create the local variable which I use to test the schema against.

I would like to move this code into the package library so that all this code is in the one place (as this feature is designed for). Since each API has a different schema to do this, I need to be able to pass this variable into the Package.

I have tried setting and getting the variable via pm.collectionVariables.set/get and pm.global.set/get.

Setting this variable in either a pre or post script returns the error “ReferenceError: schema is not defined”.

Is there a way to do this? I was hoping there would be the ability to add a parameter to the package call, or to pass in a collection variable, but I can’t see one.

Thanks

  • Platform Details:
    Version
    11.0.6
    UI version
    11.0.6-ui-240502-1530
    Desktop platform version
    11.0.4
    Architecture
    x64
    OS platform
    win32 10.0.22631

Hi @birddog-davek. Welcome to the Postman Community!

Since Packages can contain JavaScript functions, you can pass variables into them as you would in a regular functions in javascript. To simulate your scenario, take a look at the screenshots below.

Here, I have a package that exports two functions. One validates my API status code, and the other validates my response JSON against a given schema. Both of these functions take in external variables.

Here, you can see the schema being passed into the validator to check against the provided response.

1 Like

Thanks for that super concise answer, and this is exactly what I was hoping for. I hadn’t thought about having functions inside of the packages, I was thinking about the package itself as a function.

Cheers for the screenshots too, these really help me, and hopefully others, to see how to implement this.

I’m glad you found it helpful @birddog-davek. Cheers!!

@gbadebo-bello I’ve got one more question related to your screenshots.

In them you use the variable “code” that is passed in as an argument to the function as part of the title of the test. When I try to do this all I get back is the ${code} string, not the 200 that is passed in.

Do you know why?

image

Hi @birddog-davek. In your screenshot, you’re making use of template literals. Template literals work only with backticks(`), you’re using an apostrophe/single quote instead.

When you use a single quote in JavaScript, it effectively becomes a string. You need to modify line 2 in your screenshot to

return pm.test(`Returns response status code: ${code}`, () => {

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.