如何将Azure ML预测实验及API密钥嵌入网站或个人作品集
Hey there! Let's break down how to embed your Azure ML Studio prediction experiment into your website or portfolio so others can use it directly. I’ve walked through this process a few times, so here’s a practical, step-by-step guide that’s easy to follow:
Before jumping into code, double-check the key info from your Azure ML Studio experiment:
- The prediction endpoint URL: You can find this in the "Consume" tab of your published experiment. It’ll look something like
https://[your-region].azureml.net/workspaces/[workspace-id]/services/[service-id]/score - Your API key: Also in the "Consume" tab—keep this safe, it’s like a password for your API.
Never paste your API key directly into frontend JavaScript—anyone can view it via browser dev tools and misuse your service. Instead, create a simple backend endpoint that acts as a middleman between your frontend and Azure ML.
Here’s a quick example using Python Flask:
from flask import Flask, request, jsonify import requests import os app = Flask(__name__) # Store your API key in an environment variable (not hard-coded!) AZURE_ML_API_KEY = os.getenv("AZURE_ML_API_KEY") AZURE_ML_ENDPOINT = os.getenv("AZURE_ML_ENDPOINT") @app.route('/predict', methods=['POST']) def predict(): # Get input data from frontend input_data = request.json # Set up headers for Azure ML API headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {AZURE_ML_API_KEY}' } # Send request to Azure ML try: response = requests.post(AZURE_ML_ENDPOINT, json=input_data, headers=headers) response.raise_for_status() return jsonify(response.json()) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run(debug=True)
If you prefer Node.js/Express, here’s a similar snippet:
const express = require('express'); const axios = require('axios'); require('dotenv').config(); const app = express(); app.use(express.json()); const AZURE_ML_API_KEY = process.env.AZURE_ML_API_KEY; const AZURE_ML_ENDPOINT = process.env.AZURE_ML_ENDPOINT; app.post('/predict', async (req, res) => { try { const response = await axios.post(AZURE_ML_ENDPOINT, req.body, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${AZURE_ML_API_KEY}` } }); res.json(response.data); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(3000, () => console.log('Backend running on port 3000'));
Now build a simple form or input area where users can enter data, submit it, and see the prediction. Here’s a basic HTML/JavaScript example:
<!DOCTYPE html> <html> <head> <title>ML Prediction Tool</title> <style> .container { max-width: 600px; margin: 2rem auto; padding: 0 1rem; } .input-group { margin-bottom: 1rem; } button { padding: 0.5rem 1rem; background: #0078d4; color: white; border: none; border-radius: 4px; cursor: pointer; } #result { margin-top: 1.5rem; padding: 1rem; border: 1px solid #eee; border-radius: 4px; } </style> </head> <body> <div class="container"> <h2>Try Our ML Prediction</h2> <div class="input-group"> <label for="inputData">Enter your data (match the format your ML model expects):</label> <textarea id="inputData" rows="4" cols="50">{"data": [[value1, value2, value3]]}</textarea> </div> <button onclick="makePrediction()">Get Prediction</button> <div id="result"></div> </div> <script> async function makePrediction() { const inputData = document.getElementById('inputData').value; const resultDiv = document.getElementById('result'); try { // Send request to your backend proxy const response = await fetch('/predict', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: inputData }); if (!response.ok) throw new Error('Request failed'); const prediction = await response.json(); // Display the result resultDiv.innerHTML = `<h3>Prediction Result:</h3><pre>${JSON.stringify(prediction, null, 2)}</pre>`; } catch (error) { resultDiv.innerHTML = `<p style="color: red;">Error: ${error.message}</p>`; } } </script> </body> </html>
- Deploy your backend to a service like Azure App Service, Heroku, or a VPS. Make sure to set the environment variables for your Azure ML API key and endpoint.
- Host your frontend alongside the backend, or serve it from a static host (like GitHub Pages) and update the fetch URL to point to your deployed backend.
- Test the flow: enter sample data, submit, and verify you get a valid prediction from Azure ML.
- Use environment variables: Never hard-code your API key in any code that gets pushed to version control.
- Rate limiting: Add rate limiting to your backend to prevent abuse of your Azure ML service.
- Input validation: Add checks in your frontend and backend to ensure users submit data in the correct format expected by your model.
- Error handling: Make sure your frontend shows friendly error messages if something goes wrong (e.g., invalid input, API downtime).
That’s it! With this setup, visitors to your portfolio can interact with your ML model safely without you exposing sensitive credentials.
内容的提问来源于stack exchange,提问作者Omotunde Adebayo

