Julian
Julian

Reputation: 4055

How to send wiremock stub responses driven by header value

I need to build a stub with wiremock and have it return a response or another based on a certain header using a simple rule:

    {
      "request": {
        "request": {
          "method": "POST",
          "urlPattern": "/v1/my/path"
        }
      },
      "response": {
        "headers": {
          "Content-Type": "application/json"
        },
        "bodyFileName": "files/{{request.headers.<first.three.characers.of.my.header matching 400/500 or 202 otherwise>}}-response.json"
      }
    }

Thanks you in advance for your inputs

Upvotes: 1

Views: 5270

Answers (1)

agoff
agoff

Reputation: 7125

If you wanted only a single mapping, then you'd have to write a custom extension to achieve that. I don't believe there is intelligent enough parsing to only return the first three characters. Additionally, you'd need to have a JSON file for each status code that could potentially be sent in the header.

Instead, you could have three separate mappings that contain the matching you want.

{
    "priority": 1,
    "request": {
        "url": "/some/path",
        "headers": {
            "some-header": {
                "matches": "400.*"
            }
        }
    },
    "response": {
        "status": 400,
        "bodyFileName": "some-400-response.json",
    }
}

{
    "priority": 1,
    "request": {
        "url": "/some/path",
        "headers": {
            "some-header": {
                "matches": "500.*"
            }
        }
    },
    "response": {
        "status": 500,
        "bodyFileName": "some-500-response.json",
    }
}
{
    "priority": 2,
    "request": {
        "url": "/some/path"
    },
    "response": {
        "status": 200,
        "bodyFileName": "some-other-response.json",
    }
}

The two major things happening in these mappings are:

  • using priority (1 for the specific 400/500 cases, 2 for the general case)
  • matching on header value (regex matching on the first three characters and then (.*) for the rest of the header)

Upvotes: 2

Related Questions