Share this page

# Swagger API testing

DevWeb scripts can be used as part of your API performance testing. To shorten scripting time, you can use the Offline Script Generator to convert Swagger API documentation into JavaScript functions, providing a format that is easy to read and maintain. The generated functions can be called from DevWeb scripts.

Tip: Check out the video: API testing with DevWeb scripts.

In this topic:

## About API functions with DevWeb scripts

Swagger is an open specification used to describe and document RESTful APIs.

To enable testing with DevWeb scripts, a method is provided for converting the API calls in Swagger definition files (swagger.json format) into functions that can be called from DevWeb tests.

This functionality is supported with Swagger Specification 2.0.

### Using Swagger mode to generate swaggerApi.js

The Offline Generator is used in Swagger mode to generate the required files. When you add an argument containing the path or URL for a swagger.json file to the Offline Generator, the resulting output is a JavaScript file, swaggerApi.js, containing auto-generated JavaScript functions.

Note: Swagger mode also generates (or regenerates) a main.js file, but without the API function calls inside.

Each function includes parameters, and represents an API call in the Swagger definition file. The function can connect with the server to execute the operation described by the API call.

After generating the swaggerApi.js, you can import the file to the folder for a DevWeb script. From the script, you can then call the function you want to test, using the required parameters. Implementation is inside the swaggerApi.js. When the function is called, it generates an API call on the application, and returns a web request.

### Using Swagger mode with a HAR file

Your swagger.json may be very large, with hundreds of operations, and you may not want to test them all. Instead, you have the option to directly generate a script based on a HAR file, containing just the relevant operations. This is the recommended way to create your API test script; it is quicker and easier than editing a script manually to call the functions.

When you add the HAR path (and the swagger.json path or URL) to the arguments for the Offline Generator using Swagger mode, the tool generates a main.js file containing the relevant function calls, in addition to creating the swaggerApi.js file.

The creation of each function call in the main.js is based on the Offline Generator finding a single, unique match between the HAR entry and the generated JavaScript function in the swaggerApi.js. If there is a match, it creates a function call for that function. If a match is not found, or there are multiple matches, it generates a regular WebRequest send call.

## Example

A pet store application is described using the pet_swagger.json file. The JSON contains various different operations for the pet store.

pet_swagger.json file:

The JSON section below defines an API operation for adding a pet to the store, with operationID "addPet". It should be called using a POST request with an argument in its body. The parameter name is "body".

    "/pet": {
                "post": {
                    "tags": [
                        "pet"
                    ],
                    "summary": "Add a new pet to the store",
                    "description": "",
                    "operationId": "addPet",
                    "consumes": [
                        "application/json"
                    ],
                    "produces": [
                        "application/json",
                        "application/xml"
                    ],
                    "parameters": [
                        {
                            "in": "body",
                            "name": "body",
                            "description": "Pet object that needs to be added to the store",
                            "required": true,
                            "schema": {
                                "$ref": "#/definitions/Pet"
                            }
                        }
                    ],
                    "responses": {
                        "405": {
                            "description": "Invalid input"
                        }
                    },

swaggerApi.js file:

When the Offline Generator generates the swaggerApi.js file, it contains the corresponding generated function for addPet. It has a parameter named body, as used in the JSON file, and the parameter description from the JSON file.

The function creates a WebRequest to call the API, and returns the request. In the body, the function used the parameter.

main.js file:

When the Offline Generator generates the main.js file, it contains a call to the addPet function in the swaggerApi.js, using the value taken from the HAR file. The function uses the returned WebRequest and sends it. The return value of the send is a WebResponse, which is assigned to a variable.

Tip: The <DevWeb root folder>\examples\ folder includes the following API testing example scripts:

- APITestingPetStore

- APITestingAdvantageOnlineShopping

## Parameters

- Swagger describes several locations of function parameters: Path, Headers, Query, Form Data, and Body.

  The generated function accepts the parameters defined for the operation in the swagger file, and used in the function body, inside the generated WebRequest. For example, Path parameters are used in the WebRequest URL, Query parameters are used in the WebRequest query.

- A parameter has a required property in its schema which can be equal to true or false. All parameters are generated, whether required or not. The Offline Generator ignores this property.
- The functions getSchema and getHost (that return the Schema and Host parameters respectively) are used in the WebRequest URL.

- If the swagger.json is missing the Host property, the generated getHost function returns an empty string, and the script will fail with an error. To avoid this, the main.js file includes an override option for getHost, to prompt you to add your host name:

## Correlations for API testing functions

The API functions calls may include correlation extractors and appliers, where relevant. When the record scan and rules scan are enabled and find correlation values, the values are added to the generated API function calls.

For more information on correlation rules, see Correlate dynamic values.

### Extractors

When generating API function calls, the relevant extractors (defined by the correlation record or rule scan) are automatically generated in the main.js file.

Example:

    let webRequest1 = swaggerApi.createSomething("1001", "1002", `{
              "data": [{
                      "description": "DevWeb API test1",
                      "name": "Created by Some User"
                  },
          		{
                      "description": "DevWeb API test2",
                      "name": "Created by Some User"
                  }
              ],
              "exceeds_total_count": false,
              "total_count": 2
          }
          `);
        webRequest1.extractors = [
            // Source='Rule' Original value="2001"
            new load.BoundaryExtractor("test1", {
                    leftBoundary: "[{\"type\":\"test\",\"id\":\"",
                    rightBoundary: "\"},{\"type\":\"test\",\"id\":\"2002"
                }),
            // Source='Rule' Original value="2002"
            new load.BoundaryExtractor("test2", {
                    leftBoundary: ",{\"type\":\"test\",\"id\":\"",
                    rightBoundary: "\"}],\"exceeds_total_count"
                }),
        ]
        const webResponse1 = await webRequest1.send();

### Appliers for values exposed in the script

For the API function call parameters that are exposed, where you see the values in the main.js, the applier simply replaces the correlated value.

Example:

A function call has a parameter requiring a correlated value for an API key. This was extracted from an earlier web response:

let webRequest = swaggerApi.deletePet(`API_KEY_11122FFFFF`, "123");

After a record scan or rule scan, it becomes:

let webRequest = swaggerApi.deletePet(`${earlierResponse.extractors['api_key']}`, "123");

### Appliers for attributes not exposed in the script

When generating API function calls, there are web request attributes that do not appear in the parameters, and are therefore not exposed in the main.js. For example, some headers or query strings.

If these attributes have values that need to be correlated, they are accessed directly by the record or record scan, and generated in the main.js like an assignment, using the request name. The appropriate applier is then applied to the appropriate field.

Example:

     let webRequest4 = swaggerApi.addPet(`{
            "id": 10,
            "authCookie": `${webResponse2.extractors['authCookie']}`,
            "category": {
              "id": 0,
              "name": "string"
            },
            "name": "Dog",
            "photoUrls": [
              "string"
            ],
            "tags": [
              {
                "id": 0,
                "name": "string"
              }
            ],
            "status": "available"
          }`);
        webRequest4.headers["my_session"] = `${webResponse2.extractors['SessionId']}`
        webRequest4.queryString["authCookie"] = `${webResponse2.extractors['authCookie']}`
        const webResponse4 = await webRequest4.send();

## Generate files from Swagger definitions

The following steps describe how to generate swaggerApi.js and main.js files using Swagger mode.

To generate files from Swagger:

Prerequisite: A swagger.json file created with Swagger Specification 2.0

1. If you want to generate a DevWeb script for specific API operations in Swagger, record and create a HAR file (refer to Using Swagger mode with a HAR file, above). Record while invoking the API calls you want to test.

   Use the Proxy Recorder or another recording method - for details, see Record and generate a script.

2. Run the Offline Script Generator from the command line or from your IDE, with the relevant argument.

   To generate the swaggerApi.js (plus main.js without the API function calls):

   OfflineGenerator.exe –mode=swagger <swagger.json path> <script directory path>

   To generate the swaggerApi.js, without regenerating the main.js file:

   OfflineGenerator.exe -mode=swagger -generateScript=false <swagger.json path> <script directory path>

   To generate swaggerApi.js and main.js using HAR file (generated in step 1 above):

   OfflineGenerator.exe –mode=swagger -level=pages -har=<path to har file> <swagger.json path> <script directory path>

   The key values are as follows:

   Parameter | Description
   --- | ---
   -mode | The mode type (swagger), to indicate the format of the source definition file.
   -generateScript=false | When the flag is defined as false, it instructs DevWeb to regenerate the API functions for the swaggerApi.js, without regenerating the main.js. This is useful if you do not want to overwrite manual edits in the main.js. This is relevant for simple swagger mode only (when generating functions from the JSON file, without a HAR file). If a main.js does not exist (for example, when generating swaggerApi.js for the first time), then a main.js file is generated.
   -level (Optional) | The script level to generate: a url-based script, or pages with a resource-based script. Value: url (default) or pages
   -har (Optional) | The path to the recorded HAR file from which to generate the main.js file for the script.
   <swagger.json path> | The full path or URL for the source swagger.json file.
   <script directory path> | The full path to the directory in which to save the generated files.

   Example:

   OfflineGenerator.exe -mode=swagger -level=pages -har=..\ScriptFolder\swagger_pet_store\mypc.ny.net.har http://mypc.ny.net:8080/v2/swagger.json ..\ScriptFolder\swagger_pet_store

   For more information on using the Offline Generator, see Offline Script Generator tool.

## Integrate Swagger definitions using the MCP server

Note: The ability to add Swagger API specifications and edit function parameters using the MCP server is supported from version 26.3.

When using an AI agent with the DevWeb MCP server, you can use natural language commands to create DevWeb scripts from Swagger definitions, and modify function parameters.

Instead of manually coding requests or editing script files directly, you provide the AI agent with a Swagger file, and describe the intended user flow. The agent can interpret the request, control DevWeb through the MCP server, and automatically create and run the performance test for you.

The agent can also understand allowed values defined in the API. It can extract enum values, such as account types and supported countries, and convert them into reusable test data for the performance script.

The following procedure describes a possible workflow.

To run tests with Swagger definitions using the MCP server:

1. Set up the integration with the DevWeb MCP server. For details, see MCP integration.

2. Provide the AI agent with the swagger.json file and enter an instruction to create a DevWeb script.

   The AI agent invokes the Offline Generator, and DevWeb then automatically creates a complete test script, including a main.js file, and the swaggerApi.js wrapper file containing the ready-to-use API functions. Each endpoint defined in the Swagger file becomes a callable function, such as Login, Register, Password change, and so forth.

3. In the AI chat, describe the user flow that you want to test in plain language. For example, registering a new user. The agent reads the schema definitions from the Swagger file and builds a valid request payload, based on the API specification.

4. Describe changes you want to make to the script, or to refine function parameters. For example:

   - Extracting the enum values and adding array objects to the main.js.

   - Appending a unique user suffix, so that each test iteration registers a completely new user.

   The AI agent modifies the script and parameters according to your instructions.

5. Direct the AI agent to run the script. For example: Run the script for 3 iterations.

   DevWeb runs the test as instructed, and the AI chat displays the run results.

## See also

- Offline Script Generator tool
- Create scripts
- MCP integration

https://admhelp.microfocus.com Performance Engineering for Developers 8942
Tips to improve your search results... OpenText™ Performance Engineering for Developers Help Center OpenText™ Performance Engineering for Developers Help 26.1-26.3 All View Local Help Center View Online Help Center Version: