Apidog Docs
πŸ‡ΊπŸ‡Έ English
  • πŸ‡ΊπŸ‡Έ English
  • πŸ‡―πŸ‡΅ ζ—₯本θͺž
HomeLearning CenterSupport CenterAPI References
HomeLearning CenterSupport CenterAPI References
Discord Community
Slack Community
X / Twitter
πŸ‡ΊπŸ‡Έ English
  • πŸ‡ΊπŸ‡Έ English
  • πŸ‡―πŸ‡΅ ζ—₯本θͺž
  1. Environments & variables
  • 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. Environments & variables

Using variables

In Apidog, variables allow you to save and reuse values easily. Storing a value as a variable enables you to access it across various environments, requests, scripts, and test scenarios. Utilizing variables increases productivity and promotes teamwork among colleagues.

What are variables#

A variable is a symbolic representation of data that allows you to retrieve a value without manually inputting it every time it's needed. This can be beneficial for reusing the same values across different locations. By using variables, your requests become more adaptable and easier to understand by hiding the specific details.
For instance, when you have the same token in multiple requests and anticipate changes to it in the future, you can save the token as a variable named {{my_token}} and utilize it in your requests by putting {{my_token}} in the request param value. Each time the token changes, the variable value will update it throughout your requests, wherever the variable is used.
image.png
This concept can be applied to any repeated data in your requests. The stored value in a variable will be included wherever the variable is referenced when your requests are executed. Varables could take effect in param values, in bodies, in URLs or in headers.
In Apidog's Tests module, variables can be used to pass data between requests.

Variable scopes#

Apidog offers support for variables in various scopes, allowing you to adjust your processes to different development, testing, and collaboration requirements. The scopes in Apidog correspond to the contexts in which your requests operate, and each scope serves a unique purpose.
Arranged from the widest to the narrowest scope, these include: global, environment, data, and local variables.
Global variablesallow data to be shared across requests, scripts, and environments. Their wide scope makes them perfect for testing and initial experimentation. There are two types of global variables:
Global Variables Shared within Project: These variables are accessible across an entire project and are perfect for sharing data between different endpoints. For example, you can extract a token from a login endpoint and store it as a global variable, which can then be used for authentication in other endpoint requests.
global-variables-shared-within-projects.jpg
Global Variables Shared within Team: These variables can be shared throughout the entire team and are perfect for sharing data between different endpoints across different projects. They are useful for situations where variables like a token must be shared between separate projects, such as using a token from a login project for authentication in a finance project β€” a typical scenario in microservices architectures.
global-variables-shared-within-teams.jpg
NOTE
1.
On the environment management page, you can only view and update the current values of existing team global variables. Adding, deleting, or renaming variables, as well as changing their initial values, is not allowed here.
2.
When running endpoints, you can use pre/post processors to extract or set variables as team global variables. However, you can only modify their current values β€” you cannot change their names or initial values.
3.
To add, delete, or manage team variables, you need team admin permissions. These actions can only be performed in the Team Resources > Variables.
Environment variables allow you to target your work to specific environments, such as local development, testing, or production. When switching environments, the values of the environment variables for the current environment take effect. Only one environment can be active at a time.
Data variables are sourced from external CSV or JSON files to define datasets in test scenarios or in the Apidog CLI. These variables have transient values that do not persist after a request or collection run.
Local variables are temporary variables confined to a single request or test scenario run and disappear once the run is completed. Local variables are useful for temporarily overriding other variable scopes without maintaining the value after execution.
When a variable with the same name is defined in different scopes, the value from the narrower scope will take precedence. In other words, the priority of variable effectiveness is global< environment < data < local.
For instance, if there is a global variable named "id" and a local variable also named "id", the value of the local variable will be utilized when the request is executed.
Variables in Apidog are stored as strings. When saving objects or arrays, make sure to use JSON.stringify() to convert them to strings before storing, and use JSON.parse() when retrieving them.

Initial and current values#

Each variable has an Initial value and Current value.
Initial value represents the value set within the element (environment or globals) where the variable is established. This value is synchronized with Apidog's servers and is shared with your team when you share that specific element. Setting an initial value can be beneficial for collaborating with teammates. However, please be aware that the data within an initial value will be shared with others and potentially be accessible to the public.
Current value is utilized when sending a request. These are local values that are not synchronized with Apidog's servers. Changes made to a current value are not permanently saved in the original shared API documentations, environment, or globals.
image.png
Current value is only saved locally, making it suitable for storing sensitive data such as passwords, tokens, etc. This data is not synchronized with other team members, allowing each individual to utilize their own current value seperately and securely.
If you do not need to use a personal Current Value, you can leave the Current Value empty. In this case, the Current value will follow the Initial value. However, if you input a value in the Current value field, the variable will no longer use the Initial value.
You can also click on the link icon πŸ”— next to the Current value to rebind the Current value to the Initial Value.
Since the current values are only stored locally, using cleaning software to clean the Apidog file cache will cause the current values to be deleted. So please be cautious.
When changing devices, the current value does not automatically migrate with your account. You can achieve migration by using the export-import environment feature.
If you are using Apidog Web, the current value is stored in your browser data.

Using variables in Apidog CLI#

After setting up your Test Scenario in the Apidog client, you can run this scenario using the Apidog CLI on any machine.
It's important to note that when running in the client, the current value of variables is used, while in the CLI, the initial value of variables is used. If the results of running in the client and the CLI differ, this is often the reason.
Learn more about the Apidog CLI.

Defining variables#

There are several ways to define variables, depending on where your variable values come from. You can preset variable values in the Environment Management popup, extract variables or perform database operations in the pre/post-processors, or set variable values using custom scripts.

Preset variable values in environment management#

You can preset values for global variables and environment variables in the "Environment Management" popup by following these steps:
1
Click on the "Environment Management" button ≑ in the top right corner of the interface.
2
Switch to "Global Variables" or a specific environment.
3
Add the variable name,initial value and current value.
4
Click Save.
Variables' Initial Value can only be set in the environment popup. When using processors and scripts, you can only set the Current value of variables but not the Initial value.

Add an "Extract Variable" operation#

Apidog supports visually extracting values from the API response and saving them as variables. Follow these steps:
1
In the Run tab (DESIGN Mode) or Request tab (DEBUG Mode), navigate to Post Processors.
2
Hover over "Add PostProcessor" and select "Extract Variable".
image.png
3
Enter the Variable Name and choose the Variable Scope.
Select the extraction source, such as Response JSON, Response XML, or Response Text, etc.
4
If the response is in JSON/XML format, you can utilize JSONPath/XPath syntax to parse a specific part of the Response JSON/XML and save it as the value of the variable.
image.png
5
After clicking "Send" to send the request, the variable extraction will be executed, and you can view the logs in the Console.
image.png
Learn more about Extract Variable

Setting variables in scripts#

You can easily set variables in your pre or post operation scripts using thesetmethod. Below is an example:
pm.environment.set('variable_key', 'variable_value');
Syntax forset:
1.
Environment Variables
// Set an environment variable  
pm.environment.set('variable_key', 'variable_value');  

// Unset an environment variable  
pm.environment.unset('variable_key');
Environment variables can hold different types of data, such as arrays, objects, and strings. For non-string data like objects or arrays, you need to convert them to a string usingJSON.stringify before storing them:
var array = [1, 2, 3, 4];  
pm.environment.set('array', JSON.stringify(array));  

var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };  
pm.environment.set('obj', JSON.stringify(obj));  
To read the stored data, useJSON.parseto convert it back:
try {  
  var array = JSON.parse(pm.environment.get('array'));  
  var obj = JSON.parse(pm.environment.get('obj'));  
} catch (e) {  
  // Handle exception  
}
2.
Global Variables
Global variables shared within the project:
// Set a global variable  
pm.globals.set('variable_key', 'variable_value');  

// Unset a global variable  
pm.globals.unset('variable_key');  
Global variables shared within the team:
// Set a team-shared global variable  
pm.globals.set('variable_key', 'variable_value', 'TEAM');  

// Unset a team-shared global variable  
pm.globals.unset('variable_key', 'TEAM');  
3.
Local variables
// Set a local variable  
pm.variables.set('variable_key', 'variable_value');  

// Unset a local variable  
pm.variables.unset('variable_key');  
Learn more about scrip syntax.

Fetching variable values from database#

Apidog offers a unique feature: connecting to a database to retrieve data, setting it as a variable, and using it in requests. Here are the steps:
1
In the Run tab (DESIGN Mode) or Request tab (DEBUG Mode), navigate to Post Processors.
2
Hover over "Add PostProcessor" and select "Database operation".
image.png
3
Name the database operation and set up the database connection. Learn more about Database connections.
image.png
4
Enter the SQL command. The command supports using {{variables}} within it.
5
Set "Extract Result To Variable". JSONPath is supported.
6
Click Send to execute the request. You can view the database operation's results in the Console.
image.png
Learn more about Database operations.

Using variables#

In Apidog, you can use double curly braces to reference variables across your project. For example, to refer to a variable named "username" in your request authorization settings, enclose the variable name within double curly braces like: {{my_variable}}.
When you run an endpoint, Apidog will resolve the variable and replace it with its current value.
image.png
For instance, in a request URL where a variable is referenced, such as:
http://127.0.0.1/pet/findByStatus?status={{CurrentStatus}}
Apidog will use the stored value of the CurrentStatus variable when running the request. If the value of CurrentStatus is "available", the request will be sent to the URL including the query parameter:
http://127.0.0.1/pet/findByStatus?status=available
You can view the assembled request in the "Actual request" tab.
When referencing a variable within a request body, enclose the reference in double quotes, like:
{ 
    "status" : "{{CurrentStatus}}"
    "quantity" : {{TotalPet}}
}
Double quotes are desired when using variables for string type in json format. Do not add double quotes for any other types, as shown in the example above.
Double curly braces may sometimes trigger incorrect JSON format warnings. You can ignore these warnings.
Variables can be used in request URLs, parameters, headers, authorization settings, request bodies, and header presets.
Sometimes, you may encounter an "Unresolved variable" notification, indicating that the variable is not defined in the environment or global variables. However, this may not necessarily be a problem. If you are extracting variables in a post-processor or using a script to set variables, the values may not be obtained before running the request. If they are local variables, they might expire after execution, which would also result in the variable value being unavailable. Therefore, you can first send the request to verify if there is an issue.

Accessing subelement values of variables#

If the value of the variable is in the form of an object or an array, the value of the attribute in the variable can be read by {{variableName.attributeName}} or {{variableName[0].attributeName}}. For example:
1.
The object variable user is as follows:
You can reference the name property of the user object as {{user.name}} in the API parameter.
You can reference the name property in the user object as pm.variables.get("user.name") in customized scripts.
2.
The array variable user is as follows:
You can reference the name property of the first element in the user array as {{user[0].name}} in the API parameter.
You can reference the name property in the first element of the user array as pm.variables.get("user[0].name") in customized scripts.
Reading the value of a property in a variable (object or array) as {{user.name}} follows the JSONPath syntax specification. You can replace the \$ symbol in the JSONPath with the variable name.
View details of JSONPath.

Using variables in scripts#

When using variables in scripts, you cannot directly use the syntax {{variable}}. Instead, you need to first assign the variable value to a variable using the get method. Here is an example of how to do this:
Here are more syntax about get:
1.
Environment Variables
// Fetch an environment variables
var variable_key = pm.environment.get('variable_key');
Environment variables can store data in various formats, such as arrays, objects, and strings. For non-string data like objects or arrays, you need to useJSON.stringifyto store them properly:
// Store an array  
var array = [1, 2, 3, 4];  
pm.environment.set('array', JSON.stringify(array));  

// Store an object  
var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };  
pm.environment.set('obj', JSON.stringify(obj));  
When fetching such data, you must useJSON.parseto convert it back to its original format:
try {  
  var array = JSON.parse(pm.environment.get('array'));  
  var obj = JSON.parse(pm.environment.get('obj'));  
} catch (e) {  
  // Handle exceptions  
}
2.
Global Variables
Global variables shared within the project:
// fethch global variables shared within project
var variable_key = pm.globals.get('variable_key');
Global variables shared within the team:
// fethch global variables shared within team
var variable_key = pm.globals.get('variable_key', 'TEAM');
3.
Local Variables
// fethch local variables
var variable_key = pm.variables.get('variable_key');

Logging variables#

You can log variable values to the Apidog Console during the execution of your requests.
To log the value of a variable in your script, utilize the following syntax:
To view the logged results, click on the Console tab in Response section.

Using data variables#

In Apidog, if you have multiple sets of data that need to be sent as request parameters, you can utilize the data variable feature. In the Test Scenario, you can import data in CSV or JSON format. Subsequently, you can reference these data variables using {{variable_name}}, where the variable name corresponds to the column name in the CSV.
When selecting this set of test data in the Test Scenario, the values of {{variables}} will be replaced with the actual data during runtime. Each row of data corresponds to one execution, and in the test report, you can view the requests and responses for each run.
For further information, refer to the guide on data-driven testing.

FAQ#

Q: Can I reference variables in mocks? In what scenarios can I use variables?
A: Variables only become real values when the request is sent. This means that variables can be used in some scenarios, but not in others.
Scenarios where you can use variables:
Requests: You can directly use {{variable}} in places like request parameters, body, path, and authentication.
Pre- and post-scripts: In these scripts, you can use pm.environment.get("variablename") or similar statements to reference variables, but cannot use {{variable}} directly.
Test scenarios: Requests in test scenarios would be sent so they are the same with requests and scripts.
Scenarios where you cannot use variables:
API specification: Default values for requests, default values and mocks for responses, cannot use variables.
Mocks: Advanced mocks and mock scripts do not support the use of variables.
Important note:
Do not set a variable's value to be another variable. That can lead to issues with properly resolving the variable values.
The key point is that variables are only resolved when the actual request is made. They cannot be used in static parts of the API definition or in mocking scenarios, as those do not involve the request being sent.
Modified atΒ 2025-01-15 10:39:49
Previous
Overview
Next
Environments & services
Built with