Skip to content

Latest commit

 

History

History
409 lines (350 loc) · 7.42 KB

File metadata and controls

409 lines (350 loc) · 7.42 KB

API Examples - Примеры использования

Базовые запросы

1. Healthcheck

curl http://localhost:8000/health

Ответ:

{
  "status": "healthy",
  "model_loaded": true,
  "timestamp": "2025-12-03T12:00:00"
}

2. Информация о сервисе

curl http://localhost:8000/

Ответ:

{
  "message": "ML Prediction Service",
  "docs": "/docs",
  "health": "/health"
}

3. Информация о модели

curl http://localhost:8000/api/v1/model/info

Ответ:

{
  "model_type": "RandomForestClassifier",
  "features": [
    "sepal length (cm)",
    "sepal width (cm)",
    "petal length (cm)",
    "petal width (cm)"
  ],
  "classes": ["setosa", "versicolor", "virginica"],
  "n_estimators": 100
}

Предсказания

4. Одиночное предсказание - Iris Setosa

curl -X POST "http://localhost:8000/api/v1/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "sepal_length": 5.1,
    "sepal_width": 3.5,
    "petal_length": 1.4,
    "petal_width": 0.2
  }'

Ответ:

{
  "prediction": "setosa",
  "probability": 0.98,
  "all_probabilities": {
    "setosa": 0.98,
    "versicolor": 0.01,
    "virginica": 0.01
  },
  "timestamp": "2025-12-03T12:00:00"
}

5. Одиночное предсказание - Iris Versicolor

curl -X POST "http://localhost:8000/api/v1/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "sepal_length": 5.9,
    "sepal_width": 3.0,
    "petal_length": 4.2,
    "petal_width": 1.5
  }'

Ответ:

{
  "prediction": "versicolor",
  "probability": 0.95,
  "all_probabilities": {
    "setosa": 0.02,
    "versicolor": 0.95,
    "virginica": 0.03
  },
  "timestamp": "2025-12-03T12:00:00"
}

6. Одиночное предсказание - Iris Virginica

curl -X POST "http://localhost:8000/api/v1/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "sepal_length": 6.3,
    "sepal_width": 2.9,
    "petal_length": 5.6,
    "petal_width": 1.8
  }'

Ответ:

{
  "prediction": "virginica",
  "probability": 0.97,
  "all_probabilities": {
    "setosa": 0.01,
    "versicolor": 0.02,
    "virginica": 0.97
  },
  "timestamp": "2025-12-03T12:00:00"
}

7. Пакетное предсказание

curl -X POST "http://localhost:8000/api/v1/predict/batch" \
  -H "Content-Type: application/json" \
  -d '[
    {
      "sepal_length": 5.1,
      "sepal_width": 3.5,
      "petal_length": 1.4,
      "petal_width": 0.2
    },
    {
      "sepal_length": 5.9,
      "sepal_width": 3.0,
      "petal_length": 4.2,
      "petal_width": 1.5
    },
    {
      "sepal_length": 6.3,
      "sepal_width": 2.9,
      "petal_length": 5.6,
      "petal_width": 1.8
    }
  ]'

Ответ:

{
  "results": [
    {
      "prediction": "setosa",
      "probability": 0.98,
      "all_probabilities": {
        "setosa": 0.98,
        "versicolor": 0.01,
        "virginica": 0.01
      }
    },
    {
      "prediction": "versicolor",
      "probability": 0.95,
      "all_probabilities": {
        "setosa": 0.02,
        "versicolor": 0.95,
        "virginica": 0.03
      }
    },
    {
      "prediction": "virginica",
      "probability": 0.97,
      "all_probabilities": {
        "setosa": 0.01,
        "versicolor": 0.02,
        "virginica": 0.97
      }
    }
  ],
  "count": 3,
  "timestamp": "2025-12-03T12:00:00"
}

8. Статистика обучающих данных

curl http://localhost:8000/api/v1/stats

Ответ (сокращенно):

{
  "statistics": {
    "sepal length (cm)": {
      "count": 150,
      "mean": 5.843,
      "std": 0.828,
      "min": 4.3,
      "25%": 5.1,
      "50%": 5.8,
      "75%": 6.4,
      "max": 7.9
    },
    ...
  },
  "sample_count": 150,
  "feature_names": [...]
}

Примеры с Python

Использование requests

import requests
import json

# URL сервиса
BASE_URL = "http://localhost:8000"

# Healthcheck
response = requests.get(f"{BASE_URL}/health")
print("Health:", response.json())

# Предсказание
data = {
    "sepal_length": 5.1,
    "sepal_width": 3.5,
    "petal_length": 1.4,
    "petal_width": 0.2
}

response = requests.post(f"{BASE_URL}/api/v1/predict", json=data)
result = response.json()

print(f"Предсказание: {result['prediction']}")
print(f"Вероятность: {result['probability']:.2%}")

Обработка ошибок

Невалидные данные

curl -X POST "http://localhost:8000/api/v1/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "sepal_length": -1,
    "sepal_width": 3.5,
    "petal_length": 1.4,
    "petal_width": 0.2
  }'

Ответ (422 Unprocessable Entity):

{
  "detail": [
    {
      "loc": ["body", "sepal_length"],
      "msg": "ensure this value is greater than or equal to 0",
      "type": "value_error.number.not_ge"
    }
  ]
}

Отсутствующие поля

curl -X POST "http://localhost:8000/api/v1/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "sepal_length": 5.1,
    "sepal_width": 3.5
  }'

Ответ (422 Unprocessable Entity):

{
  "detail": [
    {
      "loc": ["body", "petal_length"],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": ["body", "petal_width"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

Производительность

Benchmark с Apache Bench

# 1000 запросов, 10 параллельных соединений
echo '{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}' > payload.json

ab -n 1000 -c 10 -p payload.json -T application/json http://localhost:8000/api/v1/predict

Benchmark с wrk

wrk -t4 -c100 -d30s --latency http://localhost:8000/health

Интеграция в код

JavaScript/Node.js

const axios = require('axios');

async function predict(features) {
  const response = await axios.post(
    'http://localhost:8000/api/v1/predict',
    features
  );
  return response.data;
}

const features = {
  sepal_length: 5.1,
  sepal_width: 3.5,
  petal_length: 1.4,
  petal_width: 0.2
};

predict(features).then(result => {
  console.log('Prediction:', result.prediction);
  console.log('Probability:', result.probability);
});

Python с async/await

import asyncio
import aiohttp

async def predict_async(features):
    async with aiohttp.ClientSession() as session:
        async with session.post(
            'http://localhost:8000/api/v1/predict',
            json=features
        ) as response:
            return await response.json()

features = {
    "sepal_length": 5.1,
    "sepal_width": 3.5,
    "petal_length": 1.4,
    "petal_width": 0.2
}

result = asyncio.run(predict_async(features))
print(f"Prediction: {result['prediction']}")

Swagger UI

Для интерактивного тестирования API откройте:

http://localhost:8000/docs

В Swagger UI можно:

  • Просмотреть все эндпоинты
  • Увидеть схемы запросов/ответов
  • Выполнить тестовые запросы
  • Скачать OpenAPI спецификацию