In this article, we look at examples that depict how to use the Extract Variables Policy, to extract new context variables during API call processing within an API proxy. Specifically, let's explore the usage of this policy to extract variables from within a Query Parameter, Header or Payload of the request/response.
The following video outlines the extraction of variables from a Query Parameter or Header:
In the above video, the Extract Variables Policy labelled "GetZipCode" extracts the value of the query parameter, or a request header, named "ZIP", in the API request, and stores it in a new context variable named "getcityforecastbyzip.zipcode".
Configuration of Extract Variables policy:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ExtractVariables async="false" continueOnError="true" enabled="true" name="GetZipCode"> <DisplayName>GetZipCode</DisplayName> <QueryParam name="ZIP"> <Pattern ignoreCase="true">{zipcode}</Pattern> </QueryParam> <!-- Uncomment for extraction from header --> <!--<Header name="ZIP">--> <!-- <Pattern ignoreCase="true">{zipcode}</Pattern>--> <!--</Header>--> <Source>request</Source> <VariablePrefix>getcityforecastbyzip</VariablePrefix> </ExtractVariables>
In this next video, we see how to extract variable values from within XML or JSON Payloads:
In the above video, the Extract Variables Policy labelled "Extract-Temperature" extracts the value of the "Temperature" field value from either the XML payload or the JSON payload, of the API response, and stores it in a new context variable named "getcityweather.zipcode".
Configuration of Extract Variables policy - from XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ExtractVariables async="false" continueOnError="false" enabled="true" name="Extract-Temperature"> <DisplayName>Extract Temperature</DisplayName> <Source>response</Source> <VariablePrefix>getcityweather</VariablePrefix> <XMLPayload stopPayloadProcessing="false"> <Variable name="temperature" type="integer"> <XPath>//GetCityWeatherByZIPResponse/GetCityWeatherByZIPResult/Temperature</XPath> </Variable> </XMLPayload> </ExtractVariables>
Configuration of Extract Variables policy - from JSON:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ExtractVariables async="false" continueOnError="false" enabled="true" name="Extract-Temperature"> <DisplayName>Extract Temperature</DisplayName> <JSONPayload> <Variable name="temperature"> <JSONPath>$.GetCityWeatherByZIPResponse.GetCityWeatherByZIPResult.Temperature</JSONPath> </Variable> </JSONPayload> <Source clearPayload="false">response</Source> <VariablePrefix>getcityweather</VariablePrefix> </ExtractVariables>
Here are the sample API Proxies used in the above examples: