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.
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 variables
permit the sharing of data across requests, scripts, and environments within a project. They are accessible project-wide. Due to their broad scope, global variables are ideal for testing and initial experimenting. As your project progresses, consider utilizing more specific scopes.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.
:::tip[]
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 Postman's servers. Changes made to a current value are not permanently saved in the original shared API documentations, environment, or globals.
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.
:::tip[]
- 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.
:::highlight purple
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:
:::tip[]
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:
After clicking "Send" to send the request, the variable extraction will be executed, and you can view the logs in the Console.
:::highlight purple
Learn more about Extract Variable
:::
Set variables in scripts
You can set variables programmatically in your pre/post request scripts.
Method | Use-case | Example |
---|---|---|
pm.globals | Use to define a global variable. | pm.globals.set("variable_key", "variable_value"); |
pm.environment | Use to define an environment variable in the currently selected environment. | pm.environment.set("variable_key", "variable_value"); |
pm.variables | Use to define a local variable. | pm.variables.set("variable_key", "variable_value"); |
unset | You can use unset to remove a variable. | pm.environment.unset("variable_key"); |
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:
Name the database operation and set up the database connection. Learn more about Database connections.
Enter the SQL command. The command supports using
{{variables}}
within it.
:::highlight purple
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.
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}}
}
:::tip[]
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:
- The object variable user is as follows:
{
"id": 1,
"name": "jack"
}
- 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.
- The array variable user is as follows:
[
{
id: 1,
name: "jack",
},
];
- 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:
var name = pm.environment.get("variable");
Here are more syntax about get
:
Method | Use-case | Example |
---|---|---|
pm.globals.get | Get a global variable. | pm.globals.get("variable_key"); |
pm.environment.get | Get an environment variable from the currently selected environment. | pm.environment.get("variable_key"); |
pm.variables.get | Get a local variable. | 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:
console.log(pm.variables.get("variable_key"));
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.
:::highlight purple
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.