Using Policy Fragments in Azure APIM

As you get further into APIM usage, your code will invariably become more and more complicated.

It’s just the way it is – with greater code comes greater complexity.

Policy Fragments are a great way to organize your code. At first glance, it can appear that they are building mini-abstracted policy functions, but it’s important to realize that they aren’t functions.

Essentially, a fragment is a block of code that will execute procedurally within the order of code that you place it in. For this reason, when writing your fragment code it’s very important that you realize this, placing a fragment at the top of your <INBOUND> tag might have a different effect than if you placed it at the end of the <INBOUND> tag.

Borrowing from our previous example, I created a fragment that encapsulated my base connection logic (that is referencing Azure Key Vault data) which I can now embed into any place in my APIM code – whether it be a product, or directly on an API.

Once the fragment is created, it’s easy to drop it into your code, wherever that may be, and then have it instantiated at run-time.

In my case, I added the code to my product so I could re-use this logic elsewhere.

If you’re familiar with the Dataverse ODATA API, fragmenting my code in this manner will allow me to simply add other headers into one global connection and not through every product.

A simple implementation but a powerful tool to help keep your code organized and separated when working together.