How to Consume Azure Machine Learning Models from a Web Application
This guide shows you how to call an Azure Machine Learning (AML) model endpoint from a web application using both Python (Flask) and C# (ASP.NET Core). You’ll learn how to secure the request with an authentication token, send data, and handle the response.
Prerequisites
- Azure subscription with a deployed AML model endpoint.
- Endpoint URL and Primary Key (or Azure AD token).
- Python 3.8+ (for Flask) or .NET 6+ (for ASP.NET Core).
- Postman or curl for testing.
Flask (Python) Example
Tip: Install the required packages with
pip install flask requests.
# app.py
import os
import json
import requests
from flask import Flask, request, jsonify
app = Flask(__name__)
AML_ENDPOINT = os.getenv('AML_ENDPOINT')
AML_KEY = os.getenv('AML_KEY')
HEADERS = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {AML_KEY}'
}
@app.route('/predict', methods=['POST'])
def predict():
# Forward the incoming JSON payload to AML endpoint
payload = request.get_json()
resp = requests.post(AML_ENDPOINT, headers=HEADERS, json=payload)
if resp.status_code != 200:
return jsonify({'error': resp.text}), resp.status_code
return jsonify(resp.json())
if __name__ == '__main__':
app.run(debug=True)
ASP.NET Core (C#) Example
Tip: Use
dotnet add package Microsoft.Extensions.Http to ensure HttpClientFactory is available.
// Startup.cs (or Program.cs for .NET 6+)
using System.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient("AMLClient", client =>
{
client.BaseAddress = new Uri(builder.Configuration["AML:Endpoint"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", builder.Configuration["AML:Key"]);
});
var app = builder.Build();
app.MapPost("/predict", async (HttpContext http, IHttpClientFactory httpClientFactory) =>
{
var requestBody = await new StreamReader(http.Request.Body).ReadToEndAsync();
var client = httpClientFactory.CreateClient("AMLClient");
var response = await client.PostAsync("", new StringContent(requestBody, System.Text.Encoding.UTF8, "application/json"));
var content = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
return Results.Problem(content, statusCode: (int)response.StatusCode);
}
return Results.Json(JsonSerializer.Deserialize<object>(content));
});
app.Run();
Testing the Endpoint
Use curl or Postman to send a request to your web app:
# Example JSON payload
{
"data": [
[5.1, 3.5, 1.4, 0.2],
[6.2, 3.4, 5.4, 2.3]
]
}
# Curl example
curl -X POST http://localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{"data":[[5.1,3.5,1.4,0.2],[6.2,3.4,5.4,2.3]]}'
Securing Your Web App
- Store
AML_ENDPOINTandAML_KEYin Azure Key Vault or environment variables. - Enable HTTPS for your web app.
- Consider using Azure AD authentication instead of primary keys for production workloads.
Next Steps
- Integrate with Azure Application Insights for monitoring request latency.
- Implement retries with exponential back‑off for transient failures.
- Explore batch inference using Azure ML pipelines.