将后端连接到Azure API管理

这篇文章发布于一年多前,信息可能已过时。
了解如何使用ARM Template向API Management添加API。
使用operations , policy和backend等资源将API连接到您的后端。
在本文中,我们假定后端是在Azure functions实现的。
定义API
首先,在API Management设置API定义。
在API Management ,每个API都由称为operations的资源定义。
定义operations
operations是与一个API对应的资源。您可以在此资源中定义API路径和参数。
让我们看一下用于operations的ARM Template 。
1{2 "name": "[concat(parameters('serviceName'), '/', parameters('apiName'), ';rev=', parameters('apiRevision'), '/', parameters('operationName'))]",3 "type": "Microsoft.ApiManagement/service/apis/operations",4 "apiVersion": "2018-01-01",5 "dependsOn": [6 "[resourceId('Microsoft.ApiManagement/service/apis', parameters('serviceName'), concat(parameters('apiName'), ';rev=', parameters('apiRevision')))]",7 "[resourceId('Microsoft.ApiManagement/service/backends', parameters('serviceName'), parameters('backendName'))]"8 ],9 "properties": {10 "description": "GET Order",11 "templateParameters": [12 {13 "name": "orderId",14 "type": "string",15 "values": []16 }17 ],18 "responses": [],19 "policies": null,20 "displayName": "GetOrder",21 "method": "GET",22 "urlTemplate": "orders/{orderId}"23 },24 "resources": []25}请注意,该名称后面附加有rev;={apiRevision} ,因为它将被部署为其他文章1中提到的特定修订版。
网址是在urlTemplate指定的。可变参数以{orderId}格式表示。参数的详细信息在templateParameters进行了描述。
上面的示例定义orderId的类型为字符串。
对于method ,请指定HTTP方法。
从以上示例创建的API将为GET http(s)://{API Management FQDN}/api/v1/orders/{orderId} 。这次我们定义的是/orders/{orderId}部分,而/api/v1部分是在之前的apis和apiVersionSets 1中定义的。
您可以导入OpenAPI.yaml来定义API。我将在另一篇文章中介绍。
定义backends
接下来,定义backends 。
1{2 "name": "[concat(variables('serviceName'), '/', parameters('backendName'))]",3 "type": "Microsoft.ApiManagement/service/backends",4 "apiVersion": "2018-01-01",5 "dependsOn": [6 "[resourceId('Microsoft.ApiManagement/service/properties', parameters('serviceName'), parameters('propertyName'))]"7 ],8 "properties": {9 "title": null,10 "description": "Backend of API management",11 "url": "[concat('https://', parameters('functionsAppName'),'.azurewebsites.net/api')]",12 "protocol": "http",13 "credentials": {14 "query": {15 "code": ["[concat('{{', parameters('propertyName'), '}}')]"]16 }17 },18 "resourceId": "[concat('https://management.azure.com/subscriptions/', subscription().id, '/resourceGroups/', resourceGroup().name, '/providers/Microsoft.Web/sites/', parameters('functionsAppName'))]"19 }20}backends实际上是与组成API的后端服务等效的资源。这次,我们假设Azure functions HTTPTrigger Azure functions作为后端。
Azure functions的url在url指定, Azure functions的resourceId由resourceId指定。在这种情况下, Azure functions的HTTPTrigger的路由必须为HTTPTrigger orders/{orderId} 。
在credentials ,指定用于与Azure functions连接的API密钥。上面的模板示例意味着,以查询参数的形式(例如?code=xxx指定凭据,并设置由propertyName指定的字符串。凭证的值采用双重封闭的形式,例如{{credential}} 。
凭证(例如API密钥)存储在下面描述的properties资源中。此处指定的propertyName是指示保存在properties的凭据的名称。
顺便说一句,为了在此处指定Azure functions的API密钥,您需要从Azure functions获取密钥。
通常,可以使用模板函数listSecrets或listKeys来获取ARM Template键,但是对于Azure functions v2 2而言,它无法正常工作。最好使用Azure CLI 3预先获得它。