Home > OS >  Azure APIM rewrite url to have no suffix url
Azure APIM rewrite url to have no suffix url

Time:09-27

I have an API in APIM that contains different operations. One of these operation called e.g. testOp

testOp forward the request sent to it to a function app (FA) in azure. Instead of writing the FA URL explicitly in the policy, I decided to write it in named value called fa-url. so the API policy looks like this:

<policies>
    <inbound>
        <base />
        <set-backend-service base-url="{{fa-url}}" />
        <rewrite-uri template="/" />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

This named value is created via an ARM template that set the value of this named value to be the trigger URL of the FA. Here is the ARM code:

 {
      "properties": {
        "tags": [],
        "secret": true,
        "displayName": "fa-url",
        "value": "[listsecrets(resourceId(parameters('faRG'), 'Microsoft.Web/sites/functions', parameters('functionAppName'), parameters('functionName')), variables('apiFuncApp')).trigger_url]"
      },
      "name": "[concat(parameters('ApimServiceName'), '/fa-url')]",
      "type": "Microsoft.ApiManagement/service/namedValues",
      "apiVersion": "2021-01-01-preview"
    },

This Arm template and named value will generate a url that looks similar to this:

https://fa-name.xx.companything.net/api/realFunctionname?code=123456=

So, this url ends with a query parameters that ends with an equal sign. Now, the problem is: this API operation (testOp) has a URL in its definition

testOp looks similar to this:

enter image description here In another image: enter image description here

Thus, when I try to send a request via this operation to the FA, I get a 404 Not Found or 401 Unauthorized errors. After checking the trace, the reason is basically because the rewrite URL adds a '/' to the end of fa URL. so instead of sending to:

https://fa-name.xx.companything.net/api/realFunctionname?code=123456=

it sends to

https://fa-name.xx.companything.net/api/realFunctionname?code=123456=/

if I removed the rewrite URL function, I still get error, because now it will send to:

https://fa-name.xx.companything.net/api/realFunctionname?code=123456=/testOp

Is there any way to prevent adding any suffix to the backend URL? or do you have any other suggestion to solve this problem?

Note: I have also tried to set the rewrite URL to be an empty string but azure refused to save the policy when I do that.

CodePudding user response:

Ok, it seems like the only thing I need to do is to use this rewrite policy:

<rewrite-uri template="?" />

this will surprisingly make the URL looks exactly as I want, i.e.:

https://fa-name.xx.companything.net/api/realFunctionname?code=123456=
  • Related