クイックスタートガイド

数分で始める

このステップバイステップガイドに従って、mindzieStudioへの最初のAPIコールを成功させ、プロセスマイニング機能をアプリケーションに統合しましょう。

前提条件

  • API認証情報: アクセストークン、テナントID、プロジェクトID
  • ベースURL: あなたのmindzieインスタンスのAPIエンドポイント
  • HTTPSアクセス: mindzieインスタンスへの安全な接続
  • 開発環境: お好きなプログラミング言語とHTTPクライアント

認証情報がない場合はこちらを参照 Authentication Guide でAPIアクセス認証情報の取得方法を確認してください。

ステップ1: 基本接続の確認

まずは基本的な接続テストを行い、mindzieインスタンスへアクセス可能か確認します。

curl -X GET "https://your-mindzie-instance.com/api/Action/ping"

期待されるレスポンス:

{
  "status": "ok",
  "timestamp": "2024-01-15T10:30:00Z",
  "version": "1.0.0"
}

ステップ2: 認証の確認

認証済みpingエンドポイントで認証情報をテストします。

curl -X GET "https://your-mindzie-instance.com/api/Action/ping/authenticated" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "X-Tenant-Id: YOUR_TENANT_GUID" \
  -H "X-Project-Id: YOUR_PROJECT_GUID" \
  -H "Content-Type: application/json"

期待されるレスポンス:

{
  "status": "authenticated",
  "timestamp": "2024-01-15T10:30:00Z",
  "tenantId": "12345678-1234-1234-1234-123456789012",
  "projectId": "87654321-4321-4321-4321-210987654321",
  "userId": "user@company.com",
  "permissions": ["read", "write", "admin"]
}

ステップ3: 最初のAPIコール

実際にアクション履歴を取得するAPIコールを行います。

curl -X GET "https://your-mindzie-instance.com/api/Action/history?limit=5" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "X-Tenant-Id: YOUR_TENANT_GUID" \
  -H "X-Project-Id: YOUR_PROJECT_GUID" \
  -H "Content-Type: application/json"

レスポンス例:

{
  "actions": [
    {
      "actionId": "87654321-4321-4321-4321-210987654321",
      "actionType": "analyze",
      "status": "completed",
      "startTime": "2024-01-15T10:30:00Z",
      "endTime": "2024-01-15T10:32:15Z",
      "duration": 135,
      "userId": "user@company.com"
    }
  ],
  "pagination": {
    "currentPage": 1,
    "totalPages": 1,
    "totalItems": 1,
    "itemsPerPage": 5
  }
}

言語別例

JavaScript

モダンなWebアプリケーションやNode.jsバックエンド向けにfetch APIまたはaxiosを使用します。

Python

データサイエンスワークフローやバックエンド自動化でrequestsライブラリを使用します。

C#/.NET

エンタープライズアプリケーションやマイクロサービスでHttpClientを使用します。

JavaScript例

モダンなJavaScriptとfetch APIを使った完全な例:

// Configuration
const API_CONFIG = {
  baseURL: 'https://your-mindzie-instance.com/api',
  token: 'YOUR_ACCESS_TOKEN',
  tenantId: 'YOUR_TENANT_GUID',
  projectId: 'YOUR_PROJECT_GUID'
};

// Helper function for API requests
async function callMindzieAPI(endpoint, options = {}) {
  const url = `${API_CONFIG.baseURL}${endpoint}`;

  const defaultHeaders = {
    'Authorization': `Bearer ${API_CONFIG.token}`,
    'X-Tenant-Id': API_CONFIG.tenantId,
    'X-Project-Id': API_CONFIG.projectId,
    'Content-Type': 'application/json'
  };

  try {
    const response = await fetch(url, {
      ...options,
      headers: { ...defaultHeaders, ...options.headers }
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error('API call failed:', error);
    throw error;
  }
}

// Example usage
async function quickStartExample() {
  try {
    // 1. Test connectivity
    console.log('Testing connectivity...');
    const pingResult = await callMindzieAPI('/Action/ping');
    console.log('Ping successful:', pingResult);

    // 2. Test authentication
    console.log('Testing authentication...');
    const authResult = await callMindzieAPI('/Action/ping/authenticated');
    console.log('Authentication successful:', authResult);

    // 3. Get action history
    console.log('Fetching action history...');
    const history = await callMindzieAPI('/Action/history?limit=5');
    console.log('Action history:', history);

    console.log('Quick start completed successfully!');
    return history;
  } catch (error) {
    console.error('Quick start failed:', error);
    throw error;
  }
}

// Run the example
quickStartExample();

Python例

Pythonのrequestsライブラリを使った完全な例:

import requests
import json
from typing import Dict, Any

class MindzieQuickStart:
    def __init__(self, base_url: str, token: str, tenant_id: str, project_id: str):
        self.base_url = base_url.rstrip('/')
        self.headers = {
            'Authorization': f'Bearer {token}',
            'X-Tenant-Id': tenant_id,
            'X-Project-Id': project_id,
            'Content-Type': 'application/json'
        }

    def call_api(self, endpoint: str, method: str = 'GET', **kwargs) -> Dict[str, Any]:
        """mindzieへのAPIコールを行う"""
        url = f"{self.base_url}{endpoint}"

        try:
            response = requests.request(
                method=method,
                url=url,
                headers=self.headers,
                **kwargs
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"API call failed: {e}")
            raise

    def run_quick_start(self):
        """クイックスタートの実行"""
        print("mindzie API クイックスタートを開始します...")

        try:
            # 1. 接続テスト
            print("1. 接続テスト中...")
            ping_result = requests.get(f"{self.base_url}/api/Action/ping")
            ping_result.raise_for_status()
            print(f"   接続OK: {ping_result.json()}")

            # 2. 認証テスト
            print("2. 認証テスト中...")
            auth_result = self.call_api('/api/Action/ping/authenticated')
            print(f"   認証OK: {auth_result['status']}")

            # 3. アクション履歴取得
            print("3. アクション履歴取得中...")
            history = self.call_api('/api/Action/history?limit=5')
            print(f"   {len(history['actions'])}件のアクションを取得")

            print("クイックスタートが正常に完了しました!")
            return history

        except Exception as e:
            print(f"クイックスタートに失敗しました: {e}")
            raise

# 使用例
if __name__ == "__main__":
    # 認証情報を設定
    quick_start = MindzieQuickStart(
        base_url='https://your-mindzie-instance.com/api',
        token='YOUR_ACCESS_TOKEN',
        tenant_id='YOUR_TENANT_GUID',
        project_id='YOUR_PROJECT_GUID'
    )

    # クイックスタートを実行
    result = quick_start.run_quick_start()
    print(f"最終結果: {json.dumps(result, indent=2)}")

C#/.NET例

C#のHttpClientを使った完全な例:

using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

public class MindzieQuickStart
{
    private readonly HttpClient _httpClient;
    private readonly string _baseUrl;

    public MindzieQuickStart(string baseUrl, string token, string tenantId, string projectId)
    {
        _baseUrl = baseUrl.TrimEnd('/');

        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
        _httpClient.DefaultRequestHeaders.Add("X-Tenant-Id", tenantId);
        _httpClient.DefaultRequestHeaders.Add("X-Project-Id", projectId);
    }

    public async Task<T> CallApiAsync<T>(string endpoint)
    {
        try
        {
            var response = await _httpClient.GetAsync($"{_baseUrl}{endpoint}");
            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<T>(content, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"API call failed: {ex.Message}");
            throw;
        }
    }

    public async Task RunQuickStartAsync()
    {
        Console.WriteLine("mindzie API クイックスタートを開始します...");

        try
        {
            // 1. 接続テスト
            Console.WriteLine("1. 接続テスト中...");
            using var pingClient = new HttpClient();
            var pingResponse = await pingClient.GetAsync($"{_baseUrl}/api/Action/ping");
            pingResponse.EnsureSuccessStatusCode();
            Console.WriteLine("   接続OK");

            // 2. 認証テスト
            Console.WriteLine("2. 認証テスト中...");
            var authResult = await CallApiAsync<AuthResponse>("/api/Action/ping/authenticated");
            Console.WriteLine($"   認証OK: {authResult.Status}");

            // 3. アクション履歴取得
            Console.WriteLine("3. アクション履歴取得中...");
            var history = await CallApiAsync<ActionHistoryResponse>("/api/Action/history?limit=5");
            Console.WriteLine($"   {history.Actions.Length}件のアクションを取得");

            Console.WriteLine("クイックスタートが正常に完了しました!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"クイックスタートに失敗しました: {ex.Message}");
            throw;
        }
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}

// データモデル
public class AuthResponse
{
    public string Status { get; set; }
    public string TenantId { get; set; }
    public string ProjectId { get; set; }
    public string UserId { get; set; }
}

public class ActionHistoryResponse
{
    public ActionItem[] Actions { get; set; }
    public PaginationInfo Pagination { get; set; }
}

public class ActionItem
{
    public string ActionId { get; set; }
    public string ActionType { get; set; }
    public string Status { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime? EndTime { get; set; }
}

public class PaginationInfo
{
    public int CurrentPage { get; set; }
    public int TotalPages { get; set; }
    public int TotalItems { get; set; }
}

// 使用例
class Program
{
    static async Task Main(string[] args)
    {
        var quickStart = new MindzieQuickStart(
            "https://your-mindzie-instance.com/api",
            "YOUR_ACCESS_TOKEN",
            "YOUR_TENANT_GUID",
            "YOUR_PROJECT_GUID"
        );

        try
        {
            await quickStart.RunQuickStartAsync();
        }
        finally
        {
            quickStart.Dispose();
        }
    }
}

よくある問題と解決策

認証エラー

  • 401 Unauthorized: アクセストークンが正しく有効期限内か確認してください
  • 403 Forbidden: テナントID/プロジェクトIDやユーザー権限を確認してください
  • 400 Bad Request: 必要なヘッダーが全て含まれているか確認してください

接続問題

  • ネットワークタイムアウト: ファイアウォール設定やネットワーク接続を確認してください
  • SSL/TLSエラー: 証明書の有効性とHTTPS設定を確認してください
  • DNS解決: mindzieインスタンスのURLが正しいか確認してください

レートリミット

  • 429 Too Many Requests: 再試行時に指数的バックオフを実装してください
  • レートリミット監視: レスポンスヘッダーのレートリミット情報を確認してください
  • リクエスト最適化: ページネーションやフィルタリングを利用してAPIコールを削減してください

次のステップ

おめでとうございます! mindzieAPIのクイックスタートが完了しました。次はActions APIBlocks APIを使って強力な統合を構築しましょう。