javaproxyconfigwiremock

How to configure WireMock to proxy requests based on configuration file


can some WireMock guru help, please? I would like to configure WireMock to proxy forward requests based on configuration file or some variable (as additional condition on top of query paramater/body values match).

The configuration file would be simple json file (or something similar):

[
    {
        "key" : "proxyForwardRequest",
        "value" : "yes"
    }
]

The rule json file would look like:

{
    "mappings": [
        {
            "priority": 1,
            "request": {
                "method": "ANY",
                "urlPathPattern": "/.*",
                "bodyPatterns": [
                    {
                        "matchesJsonPath": {
                            "expression": "$.criteria.code",
                            "matches": "ABC"
                        }
                    }
                ]
            },
            "configFile": [
                {
                   "fileName": "config.json",
                   "matchesJsonPath": {
                            "expression": "$.proxyForwardRequest",
                            "matches": "yes"
                        }
                }
            ],
            "response": {
                "proxyBaseUrl": "https://destinationURL.com"
            }
        }]
}

Is something like this possible, please? Maybe someone already tried that and has the json config/custom code. I tried searching in WireMock documentation and was not able to find straightforward solution. Is it perhaps possible to customize it since WireMock is open-source? Thank you


Solution

  • I have searched more and found out Stateful Behavior functionality may be a solution for my problem, which is true I am satisfied with that approach:

        {
        "mappings": [
            {
                "scenarioName": "ForwardTo",
                "requiredScenarioState": "DestinationURL",
                "priority": 1,
                "request": {
                    "method": "ANY",
                    "urlPathPattern": "/.*"
                },
                "response": {
                    "proxyBaseUrl": "https://destinationURL.com"
                }
            },
            {
                "scenarioName": "ForwardTo",
                "requiredScenarioState": "Mock",
                "priority": 1,
                "request": {
                    "method": "ANY",
                    "urlPathPattern": "/.*"
                },
                "response": {
                    "proxyBaseUrl": "https://mockURL.com"
                }
            }
        ]
    }
    

    Default scenario state after WireMock start is STARTED. You need to change the scenario state to activate proper behavior by sending PUT request:

        PUT /__admin/scenarios/my_scenario/state
    {
        "state": "state_2"
    }
    

    More details can be found here: https://wiremock.org/docs/stateful-behaviour/