Filtering Data with APIM and Dataverse

In our previous post on setting up Dynamics/Dataverse to connect with Azure APIM, we looked at how to get data from Dynamics through APIM. That’s great, but what we’re trying to simplify for your users is how to filter data through a well-defined API.

Going back to our Contact example, I’m going to create a Template parameter that will allow someone to pass in the ContactId through the URL in a clean format.

You’ll notice I’ve highlighted a few areas, some not relevant to Filtering. The more you describe your APIs and their inputs, the easier it will be when users start to use your APIs. I’m a big believer in self-service and APIM has a great facility for letting users validate their code through the portal.

That said, you can see the structure of my Template parameter that is configured on the ById request.

Capturing and Setting the Filter

Now we start getting into the mishmash of C#/XML transformation that enables you to capture inputs from the user and act on them. In this case, I still have our SELECT criteria but we are now also overriding the filter criteria.

Before any of this happens though I search for my Template parameter and assign it to a local variable which I then access in the filter node

<set-variable name="ContactId" value="@(context.Request.MatchedParameters["ContactId"])" />
        <set-query-parameter name="$select" exists-action="override">
            <value>contactid,firstname,lastname,fullname,emailaddress1</value>
        </set-query-parameter>
        <set-query-parameter name="$filter" exists-action="override">
            <value>@{
                var contact = (string)context.Variables.GetValueOrDefault<string>("ContactId");
                var filter = "contactid eq " + contact;
                return filter;          
        }</value>
        </set-query-parameter>

When I go to test my new method, I’m now prompted to provide a value for ContactId.

And when I test my changes, you’ll notice that I only get back the one record.

Using Append

It is very easy with the $filter to override changes to your query parameters. I.e., at the Product, or API level I might have some different filters already in effect (i.e. only return max result sets). To ensure you’re not overwriting previously created filters, use the “Append” keyword when it comes to the exists-action parameter in the set-query-parameter.

Note: Even when you do this, you will still need to handle your own chaining syntax of “and/or” that you would normally when using the API.