Here we are, ready for another edition of API Management Best Practices, Tips, and Tricks. Today, we will address another helpful Best practice, Tip, and Trick that you must consider while implementing your API policies: how to dynamically rewrite the URI.
#5 How to dynamically rewrite the URI?
Sometimes we need to dynamically set the backend URI because we are not only exposing the API on our API Management, but we are also modernization and standardizing our API, providing a good naming convention and REST best practices.
In this exercise, we receive a query parameter as an input in our operation. We want to retrieve that value and add it to the path to the backend URI. For example:
- /static-path/my-query-parameter
Well, the good news is that this is possible and quite simple to archive. For that, we can use the rewrite-uri policy. The The rewrite-uri
policy converts a request URL from its public form to the form expected by the web service.
Note: You can only add path parameters using the policy. You can’t add extra template query parameters in the rewrite-uri policy.
But first, it is important to understand how we can retrieve the query parameter, and for that, we can use the following expression (despite the are other ways to archive that value):
context.Request.Url.Query.GetValueOrDefault("query-parameter-name", "default-value")
Now, to set up properly the rewrite-uri policy you need to apply the equivalent policy statement that should look like this:
<rewrite-uri template="@{
return "/static-path/"+context.Request.Url.Query.GetValueOrDefault("my-query-parameter", "");
}" />
I hope you enjoy this tip and stay tuned for the following Azure API Management Best practices, Tips, and Tricks.
If you liked the content or found it helpful and want to help me write more content, you can buy (or help buy) my son a Star Wars Lego!