Variables
Comprehensive guide to using variables in REST Client Next - environment, file, request, prompt, and system variables.
Variables in REST Client Next allow you to create dynamic, reusable, and environment-agnostic requests. There are two main types:
- Custom Variables - User-defined (Environment, File, Request, Prompt)
- System Variables - Pre-defined dynamic values
Variable Syntax
- Custom variables:
{{variableName}} - System variables:
{{$variableName}} - Request variable reference:
{{requestName.response.body.$.id}}(more complex)
When the same name is used, precedence order: Request Variables > File Variables > Environment Variables.
Custom Variables
Environment Variables
Defined in VS Code settings, shared across all .http files. Perfect for environment-specific values like hostnames, API keys, etc.
Configuration
"rest-client.environmentVariables": {
"$shared": {
"version": "v1",
"prodToken": "foo",
"nonProdToken": "bar"
},
"local": {
"version": "v2",
"host": "localhost",
"token": "{{$shared nonProdToken}}",
"secretKey": "devSecret"
},
"production": {
"host": "example.com",
"token": "{{$shared prodToken}}",
"secretKey": "prodSecret"
}
}
$shared- Variables available in ALL environments- Environment names at the same level (local, production, etc.)
- Variables can reference other variables (including from
$shared)
Usage
GET https:///api//comments/1 HTTP/1.1
Authorization: Bearer
Switch environments via Ctrl+Alt+E (Cmd+Alt+E on macOS) or click the environment name in status bar.
File Variables
Defined within the .http file itself. Scope: entire file.
Definition Syntax
Place anywhere in the file (before or between requests):
Accept quote and single quote.
@hostname = "api.example.com"
@port = 8080
@host = :
@contentType = application/json
@createdAt = {{$datetime iso8601}}
@modifiedBy = {{$processEnv USERNAME}}
Rules:
@variableName = valueon a single line- Variable name cannot contain spaces
- Value can include whitespace and any characters
- Use
\to escape special characters like\n - Values can reference other variables (including system variables)
You can add description for better understanding (displayed in hover):
# @variableName = value | description
@apiKey = abc123 | API key for external service
Reference
Use {{variableName}} in the file. To percent-encode the value, use {{% variableName %}}.
Features
- Go to Definition:
Ctrl+ClickorF12on variable reference - Find All References:
Shift+F12on variable (included in CodeLens if enabled) - Hover to see resolved value
Request Variables
Attach names to requests for cross-referencing. Perfect for request chaining (e.g., login then use token).
Definition
Just before the request URL:
# @name login
POST https://api.example.com/login HTTP/1.1
Content-Type: application/json
{
"username": "user",
"password": "pass"
}
###
@authToken = {{login.response.body.token}}
# @name createComment
POST https://api.example.com/comments HTTP/1.1
Authorization: Bearer
Content-Type: application/json
{
"content": "Hello World"
}
Important: Must manually trigger the named request first to populate its response before referencing it.
Reference Syntax
Form: {{requestName.(response|request).(body|headers).(*|JSONPath|XPath|Header Name)}}
Components:
requestName- The name defined with@nameresponseorrequest- Which to referencebodyorheaders- Which part- For
body:*- Entire body$.path- JSONPath for JSON responses (e.g.,$.id)//xpath- XPath for XML responses (e.g.,//user/@id)
- For
headers:- Header name (case-insensitive) - e.g.,
X-Auth-Token
- Header name (case-insensitive) - e.g.,
Examples:
@authToken = {{login.response.headers.X-Auth-Token}}
@userId = {{login.response.body.$.user.id}}
@xmlValue = {{getUser.response.body.//name}}
If resolution fails (invalid path, missing response), the literal text is sent and diagnostics appear.
Prompt Variables
Interactive input per request. Override any pre-defined variable temporarily.
The definition syntax of prompt variables is like a single-line comment by adding the syntax before the desired request url with the following syntax // @prompt {var1} or # @prompt {var1}. A variable description is also assignable using // @prompt {var1} {description} or # @prompt {var1} {description} which will prompt an input popup with a desired description message.
Before the request URL:
# @prompt username
# @prompt password
# @prompt refCode Your reference code from webpage
POST https://{{host}}/verify/{{refCode}} HTTP/1.1
Authorization: Basic :
Special Behavior: Variable names matching password, passwd, pass (any case) will be masked during input.
When you send the request, an input dialog appears for each prompt variable. Enter values and the request uses them. Values are not stored for subsequent requests.
System Variables
Pre-defined dynamic variables, format: {{$variableName}} (case-sensitive).
UUID
{{$guid}} - RFC 4122 v4 UUID
Fake Values
Generate fake data using Faker.js.
{{$faker <module>.<property> [param]}}
Common Faker Modules:
| Module | Properties | Examples |
|---|---|---|
address |
city, cityName, country, countryCode, postalCode, streetAddress, latitude, longitude |
{{$faker address.city}}, {{$faker address.postalCode}} |
commerce |
color, department, productName, price, ean |
{{$faker commerce.productName}}, {{$faker commerce.price}} |
date |
past, future, between, recent, month, weekday |
{{$faker date.past}}, {{$faker date.future 1 y}} |
finance |
account, mask, amount, transactionType, currencyCode, iban |
{{$faker finance.account}}, {{$faker finance.iban}} |
git |
branch, commitEntry, commitMessage, commitSha, tag |
{{$faker git.commitSha}}, {{$faker git.branch}} |
hacker |
abbreviation, adjective, noun, verb, ingverb |
{{$faker hacker.noun}}, {{$faker hacker.adjective}} |
internet |
avatar, email, exampleEmail, userAgent, url, ip, mac |
{{$faker internet.email}}, {{$faker internet.url}} |
lorem |
word, words, sentence, slug, paragraph, text |
{{$faker lorem.paragraph}}, {{$faker lorem.slug}} |
name |
firstName, lastName, fullName, jobTitle, prefix, suffix, title |
{{$faker name.fullName}}, {{$faker name.jobTitle}} |
phone |
phoneNumber, phoneNumberFormat, imei |
{{$faker phone.number}}, {{$faker phone.imei}} |
random |
number, float, arrayElement, objectElement, uuid, alphaNumeric |
{{$faker random.number 1000 9999}}, {{$faker random.arrayElement @array}} |
system |
fileName, mimeType, directory, fileType, commonFileName, semver |
{{$faker system.fileName}}, {{$faker system.mimeType}} |
Examples with parameters:
{{$faker string.alphanumeric 10}} // Alphanumeric string of 10 characters
{{$faker random.number 100 999}} // Number between 100 and 999
{{$faker date.past 2 d}} // Date within the last 2 days
{{$faker internet.email}} // Random email
{{$faker name.fullName}} // Full name
{{$faker phone.number}} // Phone number
Note: The complete list of modules and properties is available in the Faker.js documentation.
Random Integer
{{$randomInt min max}} - Random integer between min (inclusive) and max (exclusive)
{{$randomInt 1 100}} // 1-99
Timestamps & Dates
{{$timestamp [offset option]}}- Current UTC timestamp (seconds since epoch){{$datetime format [offset option]}}- Formatted datetime{{$localDatetime format [offset option]}}- Formatted datetime in local timezone
Formats:
rfc1123- RFC 1123 format (e.g.,Wed, 01 Jan 2020 00:00:00 GMT)iso8601- ISO 8601 format (e.g.,2020-01-01T00:00:00.000Z)"custom"or'custom'- Custom Day.js format (e.g.,{{$datetime "YYYY-MM-DD"}})
Offset Options:
y(year),M(month),w(week),d(day),h(hour),m(minute),s(second),ms(millisecond)
Examples:
{{$timestamp}} // Now
{{$timestamp -3 h}} // 3 hours ago
{{$datetime iso8601}} // Current time ISO 8601
{{$datetime iso8601 1 y}} // One year from now
{{$datetime "YYYY-MM-DD" 2 d}} // Day after tomorrow
{{$localDatetime "DD/MM/YYYY"}} // Local time, custom format
Environment Variables
{{$processEnv [%]envVarName}}- Look up local machine environment variable{{$dotenv [%]variableName}}- Read from.envfile in same directory
processEnv Examples:
# Direct lookup
GET https://api.example.com
Authorization: Bearer {{$processEnv API_TOKEN}}
# Indirect lookup (use variable name from settings)
GET https://api.example.com
Authorization: Bearer {{$processEnv %apiTokenEnvVar}}
With % prefix, uses the variable name from extension settings (rest-client.environmentVariables), allowing environment-specific values.
dotenv Examples:
GET https://api.example.com
Authorization: Bearer {{$dotenv API_TOKEN}}
Microsoft Entra ID (ex Azure Active Directory)
{{$aadV2Token [new] [cloud] [appOnly] [scopes:] [tenantid:] [clientid:]}}
See Authentication for full details.
OpenID Connect
{{$oidcAccessToken [new] [<clientId:] [<callbackPort:] [authorizeEndpoint:] [tokenEndpoint:] [scopes:] [audience:]}}
See Authentication for full details.
Variable Best Practices
- Security First
- Never commit secrets to source control
- Use environment variables or
{{$processEnv}}for API keys, passwords - Use
$sharedfor non-sensitive common values
- File-Level Constants
- Use
@variablefor constants in the file (base URLs, common headers) - You get Go to Definition and Find References for free
- Use
- Request Chaining
- Use
@nameand request variables for multi-step workflows - Reference responses from previous requests
- Order matters: define and execute named requests before referencing them
- Use
- Prompt for Dynamic Values
- Use
@promptfor one-time values (OTP, temporary codes) - Mask sensitive prompts by using
password,pass, orpasswdin name
- Use
- Leverage System Variables
{{$guid}}for unique identifiers{{$timestamp}}and{{$datetime}}for time-sensitive requests{{$faker}}for realistic test data{{$randomInt}}for random selections
- Naming Conventions
- Use descriptive names:
@authTokennot@token1 - Use lowercase with camelCase or snake_case consistently
- Avoid names that might conflict with system variables
- Use descriptive names:
Troubleshooting
Variable Not Resolving
Check:
- Variable is defined (spelling/case matters)
- For request variables: named request was executed first
- For JSONPath/XPath: syntax is correct and path exists in response
- File saved (some features require saved file)
Hover for Diagnostics
Hover over a variable reference to see:
- Resolved value
- Errors (if any)
- Source of the variable
Enable Logging
Set "rest-client.logLevel": "debug" in settings to see variable resolution in output panel.
Advanced Examples
Environment-Specific API Endpoint
"rest-client.environmentVariables": {
"$shared": {
"apiVersion": "v1"
},
"dev": {
"host": "dev.api.example.com"
},
"prod": {
"host": "api.example.com"
}
}
GET https:////users
Request Chaining with Tokens
@baseUrl = https://api.example.com/v1
# @name login
POST {{baseUrl}}/auth/login
Content-Type: application/json
{
"username": "user",
"password": "pass"
}
###
@authToken = {{login.response.body.token}}
# @name getUser
GET {{baseUrl}}/user/profile
Authorization: Bearer {{authToken}}
###
# @name createPost
POST {{baseUrl}}/posts
Authorization: Bearer {{authToken}}
Content-Type: application/json
{
"title": "My Post",
"userId": {{getUser.response.body.id}}
}
Dynamic Test Data
POST https://api.example.com/users
Content-Type: application/json
{
"email": "{{$faker internet.email}}",
"name": "{{$faker name.fullName}}",
"phone": "{{$faker phone.number}}",
"address": "{{$faker address.city}}, {{$faker address.country}}",
"createdAt": "{{$datetime iso8601}}",
"id": "{{$guid}}"
}
Using Process Environment Variables
.bashrc / .zshrc:
export API_KEY="my-secret-key"
Settings:
{
"rest-client.environmentVariables": {
"production": {
"apiKeyEnvVar": "API_KEY"
}
}
}
Request:
GET https://api.example.com/data
Authorization: Bearer {{$processEnv %apiKeyEnvVar}}