Search code examples
karate

karate framework - set header using variable as key


I have a fairly simple feature file that is setting auth headers for an HTTP call, however I want the name of the header (i.e., the key) to be configurable per env.

My config looks like this:

    var config = { 
        apiKeyHeader: 'x-first-key',
        apiKey: 'someValue';
    }

    if (env == 'test') { 
        config.apiKeyHeader = 'x-other-key';
    }

Then in a feature file:

    Scenario: call with header key
      * print apiKeyHeader
      Given path '/myApi'
      And header apiKeyHeader = apiKey
      When method get
      Then status 200 

Output from the test is something like this:

    14:00:00.123 [main] INFO com.intuit.karate - [print] x-first-key
    1 > GET http://localhost:8080/myApi
    1 > apiKeyHeader:  someValue

The variable is set correctly, however, in the header is set with the literal string apiKeyHeader. How can I make it use the value of the variable?


Solution

  • Use headers and there are ways to set a key for a JSON variable.

    * def headerKey = 'x-first-key',
    * def headerData = {}
    * headerData[headerKey] = 'someValue'
    # url, etc
    * headers headerData