Create reusable tests and scripts with OpenAPI reusable components

Avatar

In programming, “hacking” has historically meant making something do what it wasn’t originally intended to do, like using a whistle from a cereal box prize to play the tone into a pay phone to get free long distance calls. Today, it also refers to finding an inelegant solution to a problem. The word has gotten a bad rap, since it typically implies a nefarious or criminal activity. But many companies offer public APIs, empowering developers to stitch together their own customized solutions, even if the workarounds are a bit of a “hack.”

For example, if the user interface doesn’t accommodate a specific use case, and you can’t control which features get released and when, it’s time to get resourceful. APIs are an opportunity to create a workaround that suits you.

Alternative solutions for reusable tests and scripts

Postman users have asked if it’s possible to reuse tests and scripts. There isn’t a button or section in Postman that says, “Store your own reusable scripts here,” but there are many ways to accomplish this.

Some alternative solutions that might work for your particular circumstances are:

  • Creating collection-level or folder-level scripts to run with every request within the collection or folder.
  • Storing scripts in a global variable to use within the workspace.
  • Storing scripts in an environment variable to use alongside different collections.
  • Setting utility functions using any scope of Postman variables at the beginning of the collection, which can then be used throughout the collection.
  • Accessing your local file system for scripts saved on your machine.
  • Storing scripts within reusable components in an OpenAPI definition.

In this article, we’ll explore the last option in more detail.

Storing scripts within reusable components in OpenAPI

OpenAPI is the most popular API definition format that’s driving the API-first trend. Reusable components in OpenAPI are a powerful feature in designing and documenting an API. We won’t explore this capability now, but if you’re interested in learning more about it, check out an example of re-using an error schema.

In this article, we rely on reusable components to store our scripts and tests, and then use the Postman API to retrieve them when they’re needed.

create scripts in OpenAPI reusable components and reference the scripts within a collection
Create scripts in OpenAPI reusable components and reference the scripts within a collection.

Create the script

Let’s save our script within a custom component in our API definition.

  1. Create an API definition: In Postman, select APIs in the sidebar, and then select +. Enter a name for your new API, and continue without a repository. Create a new API definition for your API, and author the definition from scratch. Configure the definition as OpenAPI 3.0, YAML format, and check the option to Use a boilerplate (predefined template).
  2. Create custom components: Within the generated file called index.yaml, scroll down to the section called components. Create a custom component under components that begins with an x- prefix. Add the name of your script, test, or any other data you want to store. Add a description that is the code you want to store as text for each component. See rows 38 to 49 in this example. Optionally, add a type or other metadata that is used to remind readers and yourself about this code.
Create custom components using an `x-` prefix
Create custom components using an x- prefix.

Reference the script

Let’s retrieve the custom script and execute it in a request script.

  1. Enable YAML parsing: Store the source code for this YAML parser for JavaScript in a global variable called yaml-js. In other words, copy and paste this code into the global variables editor:
    Store source code of external library as a global variable so it can be used in a Postman script
    Store source code of external library as a global variable so it can be used in a Postman script.

    Then, under the Tests tab of the request, import yaml-js so that it can be used within the script:

    Import `yaml-js` so it can be used within the script.
    Import yaml-js so it can be used within the script.
  2. Retrieve the API definition: Use pm.sendRequest() to retrieve our API definition using the Postman API created in the previous steps. The example in the screenshot below shows the apiId and postman-api-key stored as collection variables.

    Use `pm.sendRequest()` to retrieve the API definition.
    Use pm.sendRequest() to retrieve the API definition.
  3. Use the reusable components:  Once we retrieve the reusable components from the API definition, we can use a function like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval()</a> to evaluate JavaScript code represented as a string. Note: there is a big security risk in using eval(), so make sure you know what code you are running.

    Confirm the scripts work as expected, such as logging to the console, running a test, and incrementing an integer.
    Confirm the scripts do what you expect, such as logging to the console, running a test, and incrementing an integer.

Try it out in Postman

  1. Fork the collection: Fork the example collection from above to your own workspace by clicking the “Run in Postman” button.
  2. Create an API definition: Create a new boilerplate API definition in your own workspace, and make sure to include the code from Rows 38 to 49 as seen in this example.
  3. Define variables: Add the ID for the API from the previous step and your Postman API key as collection variables. Store the source code for this YAML parser in a global variable called yaml-js.
  4. Confirm scripts work as expected: Send the call Using a script to see the components in action.
  5. Customize your own components: Update the API to customize your functions, or add new ones.

Assessing the workaround for your use case

What part of this solution works well?

  • You can organize a custom group of scripts using an x- prefix in the OpenAPI definition, such as for functions, tests, and other scripts.
  • The OpenAPI definition is in Postman already, so you can add, edit, and run the new code in Postman without switching context.
  • You can share these reusable components with team members in a team workspace.

What part of this solution does not work well?

  • This is not the intended purpose for reusable components in an OpenAPI definition.
  • The reusable components are not written in a text editor, so syntax highlighting and formatting of JavaScript is missing. It’s easier to copy and paste code into the API definition.
  • eval() poses a major security risk and the user can run malicious code or code with unintended consequences.

Does this satisfy your particular use case? If not, this was not the only way to solve this problem. For example, the YAML parser was saved as a global variable available within a workspace, but we could have also made a call to a CDN to retrieve the source code for the library. We also used the Postman API to retrieve an API definition containing our reusable components, but we could have accessed our local file system for saved scripts instead.

Feel free to explore some of the other alternatives listed above. And let us know some of your favorite hacks that you use in Postman in the comments below.

Technical review by Ian Douglas

What do you think about this topic? Tell us in a comment below.

Comment

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 thoughts on “Create reusable tests and scripts with OpenAPI reusable components

    Avatar

    Does adding reusable scripts and tests affect consumers, especially during the process of generating client stubs based on Open API specification?

      Avatar

      Consumers can set up their collection to re-use the scripts and tests in the same manner if they also have an OpenAPI specification and Postman API key. However, consumers generating a collection from the OpenAPI specification will not be impacted by the addition of the components defined within the spec. In other words, those components are saved within the spec, but then must be explicitly called upon and utilized.

    Avatar

    Thank you for the insightful article; it aligns perfectly with what I’ve been searching for. However, I’m encountering some challenges when trying to implement the process in Postman. Specifically, I keep receiving a “SyntaxError: Unexpected identifier” error. Could you offer some additional guidance or troubleshooting tips? Your assistance would be greatly appreciated. Thanks in advance!