Create Reusable Tests and Scripts with OpenAPI Reusable Components
Tags: editorspicks, general, tutorials, openapi
Published: 2023-02-13 17:09:36

---
title: Create Reusable Tests and Scripts with OpenAPI Reusable Components
published: true
date: 2023-02-09 18:34:11 UTC
tags: EditorsPicks,General,Tutorials,OpenAPI
canonical_url: https://blog.postman.com/create-reusable-tests-and-scripts-with-openapi-reusable-components/
---

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](https://www.popularmechanics.com/technology/a20762221/an-early-hacker-used-a-cereal-box-whistle-to-take-over-phone-lines/) 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](https://learning.postman.com/docs/writing-scripts/intro-to-scripts/#execution-order-of-scripts) to run with every request within the collection or folder.
- Storing scripts in a [global variable](https://learning.postman.com/docs/sending-requests/variables/#variable-scopes) to use within the [workspace.](https://dev.to/jansche/solving-problems-together-with-postman-workspaces-16hk-temp-slug-6231202)
- 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](https://www.postman.com/api-first/). 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](https://youtu.be/YRzpziA35Mg?t=1696).

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sb9185bl9m8nzvibwy3t.png)
_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**](https://learning.postman.com/docs/designing-and-developing-your-api/creating-an-api/): 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](https://www.postman.com/postman/workspace/postman-answers/api/5a01c61f-e5e1-4876-bde6-0c7c924e8282/version/3a97617a-c592-4f12-a766-fde92905d39b?tab=define). 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](https://blog.postman.com/wp-content/uploads/2023/01/image2-6-1000x640.png)
_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](https://www.npmjs.com/package/js-yaml) in a [global variable](https://learning.postman.com/docs/sending-requests/managing-environments/) called `yaml-js`. In other words, copy and paste [this code](https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.13.1/js-yaml.js) into the global variables editor:

![Store source code of external library as a global variable so it can be used in a Postman script](https://blog.postman.com/wp-content/uploads/2023/01/image5-4-1000x534.png)
_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.](https://blog.postman.com/wp-content/uploads/2023/01/image4-5-1000x155.png)
_Import yaml-js so it can be used within the script._

2. **Retrieve the API definition** : Use [`pm.sendRequest()`](https://learning.postman.com/docs/sending-requests/grpc/postman-sandbox-api/#sending-http-request-from-scripts) to [retrieve our API definition using the Postman API](https://www.postman.com/postman/workspace/postman-public-workspace/request/12959542-748c0367-6e64-4b9c-9f02-a2b8d297dc38) 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.](https://blog.postman.com/wp-content/uploads/2023/01/image6-4-1000x386.png)
_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 `eval()` to evaluate JavaScript code represented as a string. **Note** : there is [a big security risk in using `eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_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.](https://blog.postman.com/wp-content/uploads/2023/01/image1-6-1000x640.png)
_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

[![Run in Postman button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s1b9allm9z4mcubik6rb.png)](https://god.gw.postman.com/run-collection/1559645-09569095-9ffb-4aba-bbca-92b2954aabde?action=collection%2Ffork&collection-url=entityId%3D1559645-09569095-9ffb-4aba-bbca-92b2954aabde%26entityType%3Dcollection%26workspaceId%3Daa5fb3b8-0090-4b5e-b3b4-fa5c1f2d080d)
_Fork the collection to your own workspace by clicking the Run in Postman button_

1. **Fork the collection** : Fork [the example collection](https://www.postman.com/postman/workspace/postman-answers/collection/1559645-09569095-9ffb-4aba-bbca-92b2954aabde?ctx=documentation) from above to your own workspace by clicking the “Run in Postman” button.
2. **Create an API definition** : Create [a new boilerplate API definition](https://learning.postman.com/docs/designing-and-developing-your-api/creating-an-api/) in your own workspace, and make sure to include the code from Rows 38 to 49 as seen in [this example](https://www.postman.com/postman/workspace/postman-answers/api/5a01c61f-e5e1-4876-bde6-0c7c924e8282/version/3a97617a-c592-4f12-a766-fde92905d39b?tab=define).
3. **Define variables** : Add the ID for the API from the previous step and your [Postman API key](https://go.postman.co/settings/me/api-keys) as collection variables. Store the [source code](https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.13.1/js-yaml.js) for [this YAML parser](https://www.npmjs.com/package/js-yaml) in a [global variable](https://learning.postman.com/docs/sending-requests/managing-environments/) 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!) 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_

<button type="button" aria-label="Like Button" data-ulike-id="16411" data-ulike-nonce="cadd505c65" data-ulike-type="post" data-ulike-template="wpulike-heart" data-ulike-display-likers="" data-ulike-likers-style="popover"></button>

The post [Create Reusable Tests and Scripts with OpenAPI Reusable Components](https://dev.to/mjgutermuth/create-reusable-tests-and-scripts-with-openapi-reusable-components-c2-temp-slug-700244) appeared first on [Postman Blog](https://blog.postman.com).