Apidog Docs
πŸ‡ΊπŸ‡Έ English
  • πŸ‡ΊπŸ‡Έ English
  • πŸ‡―πŸ‡΅ ζ—₯本θͺž
HomeLearning CenterSupport CenterAPI References
HomeLearning CenterSupport CenterAPI References
Discord Community
Slack Community
X / Twitter
πŸ‡ΊπŸ‡Έ English
  • πŸ‡ΊπŸ‡Έ English
  • πŸ‡―πŸ‡΅ ζ—₯本θͺž
  1. Using scripts
  • Apidog Learning Center
  • Get started
    • Introduce Apidog
    • Basic concepts in Apidog
    • Navigating Apidog
    • Quick Start
      • Overview
      • Specify a new endpoint
      • Make a request to the endpoint
      • Add an assertion
      • Create a test scenario
      • Share your API documentation
      • Explore more
      • Send a request and save as an endpoint
    • Migration
      • Overview
      • Manual import
      • Scheduled import
      • Import options
      • Export data
      • Import from...
        • Import from Postman
        • Import OpenAPI (Swagger) spec
        • Import cURL
        • Import Markdowns
        • Import from Insomnia
        • Import from apiDoc
        • Import .har file
        • Import WSDL
  • Design APIs
    • Overview
    • Create a new API project
    • Endpoint basics
    • Components
    • Common fields
    • Global parameters
    • Endpoint change history
    • Batch endpoint management
    • Configure multiple request body examples
    • Schemas
      • Generate Schemas from JSON etc.
      • Build a schema
      • Overview
      • Create a new schema
    • Security schemes
      • Overview
      • Create a security scheme
      • Use the security scheme
      • Security scheme in online documentation
    • Advanced features
      • Custom endpoint fields
      • Import endpoints as test steps
      • Endpoint status
      • Appearance of parameter lists
      • Endpoint unique idenfication
  • Develop and Debug APIs
    • Overview
    • Generate requests
    • Send requests
    • Endpoint cases
    • Dynamic values
    • Validate responses
    • Design-first Mode & Request-first Mode
    • Generate code
    • Environments & variables
      • Overview
      • Using variables
      • Environments & services
    • Vault secrets
      • Overview
      • HashiCorp Vault
      • Azure Key Vault
      • AWS Secrets Manager
    • Pre/Post processors
      • Overview
      • Assertion
      • Extract variable
      • Wait
      • Database operations
        • Overview
        • MongoDB
        • Redis
        • Oracle Client
      • Using scripts
        • Overview
        • Postman scripts reference
        • Pre processor scripts
        • Post processor scripts
        • Public scripts
        • Calling other programming languages
        • Using JS libraries
        • Visualizing responses
        • Script examples
          • Assertion scripts
          • Using variables in scripts
          • Using scripts to modify request messages
          • Other examples
    • Dynamic values Modules
  • Mock API data
    • Overview
    • Smart mock
    • Custom mock
    • Mock priority sequence
    • Mock scripts
    • Cloud mock
    • Self-hosted runner mock
    • Mock language (Locales)
  • Automated tests
    • Overview
    • Test reports
    • Test scenarios
      • Create a test scenario
      • Pass data between requests
      • Flow control conditions
      • Import endpoints/endpoint cases from other projects
      • Sync data from endpoints/endpoint cases
      • Export test scenarios
    • Run test scenarios
      • Run a test scenario
      • Data-driven testing
      • Run test scenarios in batch
      • Scheduled tasks
      • Manage the runtime environment of APIs from other projects
    • Test APIs
      • Integration testing
      • Performance testing
      • End-to-end testing
      • Regression testing
    • Apidog CLI
      • Overview
      • Installing and running Apidog CLI
      • Apidog CLI Options
    • CI/CD
      • Overview
      • Integrate with Jenkins
      • Integration with Gitlab
  • Publish API Docs
    • Overview
    • API Technologies Supported
    • Quick share
    • View the API documentation
    • Publish docs sites
    • Folder tree settings
    • Custom layouts
    • Visibility settings
    • Endpoint SEO settings
    • Custom domain
    • Embedding values in document URLs
    • Documentation Search
    • Integrating Google Analytics with Doc Sites
    • CORS Proxy
    • API Versions
      • Overview
      • Create API versions
      • Publish API versions
      • Share endpoints with API versions
  • Send requests
    • Overview
    • gRPC
    • Use request proxy agents for debugging
    • SOAP/WebService
    • GraphQL
    • WebSocket
    • Socket.IO
    • SSE debugging
    • Create requests
      • Request History
      • Request basics
      • Parameters and body
      • Request headers
      • Request settings
      • HTTP/2
    • Authentication and authorization
      • Overview
      • CA and client certificates
      • Authorization types supported by Apidog
      • Digest Auth
      • OAuth 1.0
      • OAuth 2.0
      • Hawk Authentication
      • Kerberos
      • NTLM
      • Akamai EdgeGrid
    • Response and cookies
      • Overview
      • API response in Apidog
      • Create and send cookies
      • Debug requests
      • Save the request as an endpoint
  • Branches
    • Overview
    • Create a new sprint branch
    • Test APIs in a branch
    • Design API in a branch
    • Merge sprint branches
    • Manage sprint branches
  • Apidog MCP Server
    • Overview
    • Conntect API Specification within Apidog Project to AI via Apidog MCP Server
    • Conntect Online API Documentation Published by Apidog to AI via Apidog MCP Server
    • Conntect OpenAPI Files to AI via Apidog MCP Server
  • Best practices
    • How to handle API signatures
    • How to access OAuth 2.0 protected APIs
    • Apidog collaboration workflow
    • Managing authentication state in Apidog
  • Administration
    • Onboarding Checklist
      • Basic Concepts
      • Onboarding Guide
    • Managing Teams
      • Managing Teams
      • Managing Team Members
      • Member Roles & Permission Settings
      • Team Activities
      • Team Resources
        • General Runner
        • Team Variables
        • Request Proxy Agent
      • Real-time Collaborations
        • Team Collaboration
    • Managing Projects
      • Managing Projects
      • Managing Project Members
      • Notification Settings
      • Project Resources
        • Database Connection
    • Managing Organizations
      • Single Sign-On (SSO)
        • SSO Overview
        • Configure Microsoft Entra ID
        • Configure Okta
        • Configure SSO for an Organization
        • Managing user accounts
        • Mapping Groups to Teams
      • SCIM Provisioning
        • Intro to SCIM Provisioning
        • Microsoft Entra ID
        • Okta
      • Organization Resources
        • Self-hosted Runner
  • Billing
    • Overview
    • Credits
    • Unable to use credit cards?
    • Managing subscriptions
    • Upgrade plan
  • Add-ons
    • API Hub
    • Apidog Intellij IDEA plugin
    • Browser Extension
      • Chrome
      • Microsoft Edge
    • Request Proxy
      • Request proxy in Apidog web
      • Request proxy in shared docs
      • Request proxy in Apidog client
  • Account & preferences
    • Language settings
    • Data backup
    • Network proxy configuration
    • Hot keys
    • Updating Apidog
    • Generate OpenAPI access token
    • Deleting account
    • Account settings
  • References
    • API-Design First Approach
    • Apidog OpenAPI/Swagger Specificaiton Extensions
    • JSONPath
    • XPath
    • Regular Expressions
    • JSON Schema
    • CSV File Format
    • Install Java Environment
    • Runner deployment environment
    • Apidog flavored Markdown
  • Apidog Europe
    • Apidog Europe
  • Support Center
  1. Using scripts

Calling other programming languages

External programs are code files saved under the "External Programs Directory", which can be java program archive files (.jar packages), or code source files of other programs. It supports files with extensions like:
java (.jar)
python (.py)
php (.php)
js (.js)
BeanShell (.bsh)
go (.go)
shell (.sh)
ruby (.rb)
lua (.lua)
External programs run outside the "sandbox environment", with access to operate other programs, files, and data on your computer, which poses some security risks. Users should verify the security of called programs.

Calling an external program#

You can quickly open the "External Program Directory" in the following way:
When calling an external program, Apidog will start a subprocess and run the specified external program in it with command line execution. Finally the standard output (stdout) of the subprocess will be returned as the result of the call. In the whole calling process, the core logic is implemented by users in the external program, while Apidog mainly does the following 3 steps:
1.
Combine the command string based on the provided parameters
2.
Execute the command
3.
Return the result
Among them, the first step is key to understand the calling principles. Apidog uses the formula "command prefix + program path + parameter list" to concatenate the command.
The "command prefix" is inferred from the file extension of the program file. The "program path" and "parameter list" are both provided by users while calling.
For example: pm.execute('com.apidog.Base64EncodeDemo.jar', ['abc','bcd']), the actual executed command is java -jar "com.apidog.Base64EncodeDemo.jar" "abc" "bcd".
The mapping between program file extensions and command prefixes:
LanguageCommand PrefixFile Extension
Javajava -jar.jar
Pythonpython.py
PHPphp.php
JavaScriptnode.js
BeanShelljava bsh.Interpreter.bsh
Gogo run.go
Shellsh.sh
Rubyruby.rb
Lualua.lua
Rustcargo run.rs
Pythonpython.py

API#

pm.executeAsync#

filePath string External program path
args string[] Parameters. When calling specified methods in a jar package, JSON.stringify will be used for conversion. Except for that, non-string types will be implicitly converted to string.
options Object
command string The execution command of the external program, the first part of "command prefix" is the execution command. Optional, default value is inferred automatically (see "command prefix" table above), can be customized to any program.
cwd string Working directory of the subprocess. Optional, default is "External Programs Directory".
env Record<string, string> Environment variables of the subprocess. Optional, default is {}.
windowsEncoding string Encoding used on Windows system. Optional, default is "cp936".
className string Specify the class name to call in the jar package, e.g. "com.apidog.Utils". Optional, see Call specified methods in jar packages for details.
method string Specify the method name to call in the jar package, e.g. "add". Optional (required if className has value), see Call specified methods in jar packages for details.
paramTypes string[] Specify the parameter types of the method to call in the jar package, e.g. ["int", "int"]. Optional, default is inferred automatically based on parameters, see Call specified methods in jar packages for details.
Return: Promise<string>
Usage of command parameter
By default Apidog uses python to execute .py files. If python3 is already installed on the computer, command can be specified as python3.

pm.execute#

It is recommended to use pm.executeAsync instead, See Code migration instructions for details.
pm.execute(filePath, args, options)
filePath string External program path
args string[] Parameters. When calling specified methods in a jar package, JSON.stringify will be used for conversion. Except for that, non-string types will be implicitly converted to string.
options Object
windowsEncoding string Encoding used on Windows system. Optional, default is "cp936".
className string Specify the class name to call in the jar package, e.g. "com.apidog.Utils". Optional, see Call specified methods in jar packages for details.
method string Specify the method name to call in the jar package, e.g. "add". Optional (required if className has value), see Call specified methods in jar packages for details.
paramTypes string[] Specify the parameter types of the method to call in the jar package, e.g. ["int", "int"]. Optional, default is inferred automatically based on parameters, see Call specified methods in jar packages for details.
Return: string

Execution and Logs#

When executing a program, the executed command will be printed in the console (for reference only). If the result does not meet expectations, you can copy the command and paste it in Shell/CMD to debug.
The console will also print the "standard output (stdout)" and "standard error output (stderr)" of the executed process. The stdout content (excluding the trailing newline character) will be the final result of the execution.
TIP
For historical reasons, pm.execute treats execution as failed when there is content in stderr. This causes some programs to fail when outputting warnings or error messages. pm.executeAsync changes to use the exit code of the process to determine if the execution failed.

Input and output of external programs#

Parameters#

Since the specified external program runs with command line execution, it can only get the passed in parameters through command line arguments.
For example, in script pm.executeAsync('add.js', [2, 3]), the actual executed command is node add.js 2 3. To get the parameters in the external script add.js:
TIP
1.
Different programming languages have different ways to get command line arguments, please refer to corresponding language docs.
2.
The type of command line arguments is always string, need to convert based on actual types.

Return value#

As mentioned above, Apidog uses the stdout content as the result of program execution. So printing content to stdout can return results.
For example, in script const result = await pm.executeAsync('add.js', [2, 3]), the result can be returned by:
1.
Different programming languages have different ways to print to stdout, refer to corresponding language docs.
2.
The return type is string, need to convert based on actual types.
3.
The trailing newline character of the result will be trimmed.
4.
When calling specified methods in jar packages, the return value of the called method will be used as the final return value.

Throwing errors#

Throwing errors can fail the current task and stop execution. For example:
1.
Different programming languages have different ways to throw errors, refer to corresponding docs.
2.
In JavaScript, console.error('Error') only prints to stderr instead of throwing an error. Consider this while using other languages too.

Debug information#

Since pm.executeAsync uses exit code instead of stderr to determine success, stderr can be used to print debug information without affecting execution.
For example:
TIP
1.
Only pm.executeAsync supports this way of printing debug info.
2.
Different programming languages have different ways to print to stderr, refer to corresponding docs.

Migrate from pm.execute to pm.executeAsync#

Since the return value of pm.executeAsync is Promise type, execute cannot be directly changed to executeAsync. But you can use async/await to migrate with minimal changes.
TIP
Apidog version >= 2.3.24 (CLI version >= 1.2.38) supports top-level await.
Steps:
1.
Change execute to executeAsync
2.
Add await before function call

Call specified methods in .jar packages#

TIP
This feature requires Apidog version >= 2.1.39. It only supports calling jars with reflection, not jars like Spring Boot using internal runtime reflection.
By default, calling a jar will invoke the main method in the Main class. If options.className is specified, it will override the default behavior and call the specified method in the jar instead.
Calling specified methods in jars is different from other external programs. Apidog will use a built-in executor to find the method in the jar by reflection and call it. If the called method has a return value, it will be used as the final return value after converting to string. Otherwise, it works the same as other calls, using stdout content as return value.
For example:
The actually executed command is:
Where <app-dist>/assets/JarExecuter-1.1.0-jar-with-dependencies.jar is the built-in executor, responsible for finding the method com.apidog.Test.combine(String,String) in the user program ./scripts/jar-1.0-SNAPSHOT.jar through reflection, and calling it with parameters (JSON string) "hello" and "world".
TIP
paramTypes is optional. If not specified, types will be inferred automatically based on parameters. Integers are inferred as "int", floats as "double", booleans as "boolean", strings as "String", arrays are inferred based on the first element, e.g. [3] is inferred as "int[]", [3.14] as "double[]", etc.
If the inferred types do not match the actual parameter types of the called method, paramTypes needs to be specified manually.
Supported values in paramTypes array: "Number"、"int"、"Integer"、"long"、"Long"、"short"、"Short"、"float"、"Float"、"double"、"Double"、"boolean"、"Boolean"、"String"、"Number[]"、"int[]"、"Integer[]"、"long[]"、"Long[]"、"short[]"、"Short[]"、"float[]"、"Float[]"、"double[]"、"Double[]"、"boolean[]"、"Boolean[]"、"String[]"
So the paramTypes in the example above can be omitted:

Examples#

1. PHP program#

Script:
test.php:

2. Jar program#

Script:
com.apidog.utils.jar:

Common issues#

1. Some programs require project config files and will error if missing#

**Rust and Go: **
Rust:
could not find `Cargo.toml` in `<...>/ExternalPrograms` or any parent directory
Go:
go.mod file not found in current directory or any parent directory; see 'go help modules'
Solution: Use pm.executeAsync and specify cwd.

2. MacOS has built-in Python 3 but no Python 2#

Use pm.executeAsync and set command to "python3".

3. Command xxx not found#

Install corresponding program and add necessary directories to system PATH. See docs for Java installation.

4. Calling external scripts prints garbled on some Windows systems#

Set windowsEncoding to 'utf-8'
Modified atΒ 2024-08-29 10:36:15
Previous
Public scripts
Next
Using JS libraries
Built with