When we use the IntelliJ HTTP Client we can write JavaScript for the pre-request and response handlers. If we want to access an environment variable in JavaScript we can use request.environment.get(string). The argument for the get function is the name of the environment variable we want to get the value for. Environment variables can be defined in the file http-client.env.json or in http-client.private.env.json.

In the following example we have environment file http-client.env.json with two environments development and production. Each environment has a variable named project:

{
    "development": {
        "project": "DEV-1270"
    },
    "production": {
        "project": "PROJ-1234"
    }
}

In our .http request file we are posting to endpoint https://ijhttp-examples.jetbrains.com/anything and we use JavaScript to read the environment variable project:

### POST to example URL
< {%
    // Get value for environment variable 'project'.
    const project = request.environment.get("project");

    // Use split to get the value before and after the -.
    const kindAndNumber = project.split("-");

    // As an example we use the value of the environment variable
    // to assign values to new request variables.
    request.variables.set("kind", kindAndNumber[0]);
    request.variables.set("number", kindAndNumber[1]);
  %}
POST https://ijhttp-examples.jetbrains.com/anything

{
    "project": "{{project}}",
    "kind": "{{kind}}",
    "number": "{{number}}"
}

In the response we see the variables do have values:

...
"json": {
    "kind": "PROJ",
    "number": "1234",
    "project": "PROJ-1234"
  }
...

Written with IntelliJ IDEA 2023.3.3.

shadow-left