Azure API Management - Use Template parameters to set Query String parameters
In this short article I will try to explain, as simple as possible, how to use Azure API Management to translate a uncleaned URL into an clean URL. An unclean URL could be something like https://example.com/hello?name=Anders, while a clean version of that could be https://example.com/hello/Anders.
I am using a basic Logic App in Azure as Backend. It triggers on HTTP request and takes name as a query parameter. It picks it up and then respond with "Hello name". You can deploy one for yourself by using this deployment script https://github.com/anderseide/poc-logicapp-hello-name, if you want to do the exact same thing as I do below.
Configuration in API Management
After deploying the Logic App trough API Management, next step is to define a Template parameters. We do that by going to the operation we want to modify, and simply in the Frontend URL field, add the parameter using curly brackets. In this example /hello/{name}.
In the Template section, we should now see name as one of the parameters. From there we can add more information like Description, Type and default Values.
Next step is to add a Inbound policy rule for this operation. All we have to do is add the following snippet into policies.
<set-query-parameter name="name" exists-action="override">
<value>@(context.Request.MatchedParameters["name"])</value>
</set-query-parameter>
Simply explained, this policy is picking up the template parameter from the request, and passes it on to the backend as a Query parameter. If you have multiple parameters, simply repeat the process for each one. That's it!
The complete policy set should then look something like this image
Interesting?
To learn more about API Management policies used above, have a look at the following documentation
- https://docs.microsoft.com/en-us/azure/api-management/api-management-transformation-policies#SetQueryStringParameter
- https://docs.microsoft.com/en-us/azure/api-management/api-management-policy-expressions
- https://docs.microsoft.com/en-us/azure/api-management/add-api-manually#add-and-test-a-parameterized-operation
how to fetch default value of Template parameter with policies
How to make this as optional parameter? Like I want to use optional template parameter i.e. in the URL something like this I want to have /hello/{name?}. In Query parameter we can have required or not required checkbox but not for template parameter
Hi Anders Eide what should i be doing if i need to send it as a uri-parameter?