Search code examples
apigee

How to add dynamic uuid to apigee proxies?


What should be of uuid instead of {java.util.UUID.randomUUID()} to get a random UUID in every request sent to backend ?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" 
    name="HeaderAddition">
    <DisplayName>HeaderAddition</DisplayName>
    <Properties/>
    <Add>
        <Headers>
            <Header name="uuid">{java.util.UUID.randomUUID()}</Header>
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

Solution

  • I have got the solution . I have added a Javascript in the preflow to generate the uuid.Then created a assign message policy to have that variable in the request.

    JS:

     function generateUUID() { // Public Domain/MIT
        var d = new Date().getTime();
        if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
            d += performance.now(); //use high-precision timer if available
        }
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
    }
    
    var uuid = generateUUID();
    context.setVariable('x-apigee-uuid', uuid); 
    

    Assign Message Policy:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <AssignMessage async="false" continueOnError="false" enabled="true" 
    name="HeaderAddition-123">
        <DisplayName>HeaderAddition-123</DisplayName>
        <Add>
            <Headers>
                <Header name="uuid">{x-apigee-uuid}</Header>
            </Headers>
        </Add>
        <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
        <AssignTo createNew="false" transport="http" type="request"/>
    </AssignMessage>