Gestion des Blocs

Obtenir, Mettre à Jour et Supprimer des Blocs d'Analyse

Gérez les blocs d'analyse dans les notebooks. Les blocs sont les unités fondamentales d'analyse qui effectuent des transformations de données, des calculs, des opérations de filtrage et des alertes.

Test de Connectivité

Ping Non Autorisé

GET /api/{tenantId}/{projectId}/block/unauthorized-ping

Point de test qui ne nécessite pas d'authentification. Utilisez ceci pour vérifier que l'API Block est accessible.

Réponse

Ping Successful

Ping Authentifié

GET /api/{tenantId}/{projectId}/block/ping

Point de ping authentifié pour vérifier l'accès à l'API pour un locataire et un projet spécifiques.

Réponse (200 OK)

Ping Successful (tenant id: {tenantId})

Réponse (401 Non Autorisé)

{error message describing authorization failure}

Obtenir les Détails d'un Bloc

GET /api/{tenantId}/{projectId}/block/{blockId}

Récupère des informations complètes sur un bloc d'analyse spécifique, y compris sa configuration, son historique d'exécution et ses métadonnées.

Paramètres de Chemin

Paramètre Type Obligatoire Description
tenantId GUID Oui Identifiant du locataire
projectId GUID Oui Identifiant du projet
blockId GUID Oui Identifiant du bloc

Réponse (200 OK)

{
  "blockId": "550e8400-e29b-41d4-a716-446655440000",
  "notebookId": "660e8400-e29b-41d4-a716-446655440000",
  "blockType": "Filter",
  "blockTitle": "Date Range Filter",
  "blockDescription": "Filters data for the last 30 days",
  "blockOrder": 0,
  "configuration": "{\"filterType\": \"dateRange\", \"startDate\": \"2024-01-01\"}",
  "isDisabled": false,
  "dateCreated": "2024-01-15T10:30:00Z",
  "dateModified": "2024-01-15T14:45:00Z",
  "createdBy": "user@example.com",
  "modifiedBy": "user@example.com",
  "lastExecutionDate": "2024-01-15T14:45:00Z",
  "lastExecutionStatus": "Success",
  "executionCount": 12
}

Champs de Réponse

Champ Type Description
blockId GUID Identifiant unique du bloc
notebookId GUID ID du notebook contenant ce bloc
blockType string Type de bloc (Filtre, Calculateur, Alerte, etc.)
blockTitle string Titre affiché du bloc
blockDescription string Description de l'objectif du bloc
blockOrder integer Ordre du bloc dans le notebook (par défaut : 0)
configuration string Chaîne JSON contenant les paramètres du bloc
isDisabled boolean Si le bloc est désactivé
dateCreated datetime Date de création du bloc
dateModified datetime Date de dernière modification du bloc
createdBy string Utilisateur ayant créé le bloc
modifiedBy string Utilisateur ayant modifié le bloc en dernier
lastExecutionDate datetime Date de la dernière exécution du bloc
lastExecutionStatus string Statut de la dernière exécution
executionCount integer Nombre de fois que le bloc a été exécuté

Réponses d'Erreur

Introuvable (404) :

{
  "Error": "Block not found",
  "BlockId": "550e8400-e29b-41d4-a716-446655440000"
}

Mettre à Jour un Bloc

PUT /api/{tenantId}/{projectId}/block/{blockId}

Met à jour les métadonnées d'un bloc existant. Conserve l'historique d'exécution tout en mettant à jour les champs spécifiés.

Corps de la Requête

{
  "blockTitle": "Updated Date Filter",
  "blockDescription": "Filters data for custom date range",
  "isDisabled": false
}

Champs de la Requête

Champ Type Obligatoire Description
blockTitle string Non Nouveau titre pour le bloc
blockDescription string Non Nouvelle description pour le bloc
isDisabled boolean Non Indique si le bloc doit être désactivé

Réponse (200 OK)

Retourne l'objet bloc mis à jour avec la même structure que le point GET.

Réponses d'Erreur

Requête Incorrecte (400) :

Failed to update block.

Supprimer un Bloc

DELETE /api/{tenantId}/{projectId}/block/{blockId}

Supprime définitivement un bloc ainsi que tout son historique d'exécution du notebook. Cette opération est irréversible.

Codes de Réponse

  • 204 No Content - Bloc supprimé avec succès
  • 400 Bad Request - Échec de la suppression du bloc
  • 401 Unauthorized - Non authentifié ou accès refusé
  • 404 Not Found - Bloc introuvable

Création de Blocs

La création des blocs est gérée via l'API Notebook, pas l'API Block.

POST /api/{tenantId}/{projectId}/notebook/{notebookId}/blocks

Voir Notebook API pour la documentation complète sur la création de blocs.

Exemples d'Implémentation

cURL

# Test de connectivité (sans auth)
curl -X GET "https://your-mindzie-instance.com/api/12345678-1234-1234-1234-123456789012/87654321-4321-4321-4321-210987654321/block/unauthorized-ping"

# Test de connectivité (authentifié)
curl -X GET "https://your-mindzie-instance.com/api/12345678-1234-1234-1234-123456789012/87654321-4321-4321-4321-210987654321/block/ping" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

# Obtenir les détails d'un bloc
curl -X GET "https://your-mindzie-instance.com/api/12345678-1234-1234-1234-123456789012/87654321-4321-4321-4321-210987654321/block/550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

# Mettre à jour un bloc
curl -X PUT "https://your-mindzie-instance.com/api/12345678-1234-1234-1234-123456789012/87654321-4321-4321-4321-210987654321/block/550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"blockTitle": "Updated Filter", "isDisabled": false}'

# Supprimer un bloc
curl -X DELETE "https://your-mindzie-instance.com/api/12345678-1234-1234-1234-123456789012/87654321-4321-4321-4321-210987654321/block/550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

JavaScript/Node.js

const TENANT_ID = '12345678-1234-1234-1234-123456789012';
const PROJECT_ID = '87654321-4321-4321-4321-210987654321';
const BASE_URL = 'https://your-mindzie-instance.com';

class BlockManager {
  constructor(token) {
    this.token = token;
    this.headers = {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    };
  }

  async getBlock(blockId) {
    const url = `${BASE_URL}/api/${TENANT_ID}/${PROJECT_ID}/block/${blockId}`;
    const response = await fetch(url, { headers: this.headers });

    if (response.ok) {
      return await response.json();
    } else if (response.status === 404) {
      throw new Error('Block not found');
    } else {
      throw new Error(`Failed to get block: ${response.status}`);
    }
  }

  async updateBlock(blockId, updates) {
    const url = `${BASE_URL}/api/${TENANT_ID}/${PROJECT_ID}/block/${blockId}`;
    const response = await fetch(url, {
      method: 'PUT',
      headers: this.headers,
      body: JSON.stringify(updates)
    });

    if (response.ok) {
      return await response.json();
    } else {
      throw new Error(`Failed to update block: ${response.status}`);
    }
  }

  async deleteBlock(blockId) {
    const url = `${BASE_URL}/api/${TENANT_ID}/${PROJECT_ID}/block/${blockId}`;
    const response = await fetch(url, {
      method: 'DELETE',
      headers: this.headers
    });

    return response.status === 204;
  }
}

// Utilisation
const manager = new BlockManager('your-auth-token');

// Obtenir les détails d'un bloc
const block = await manager.getBlock('block-guid');
console.log(`Bloc : ${block.blockTitle} (${block.blockType})`);

// Mettre à jour un bloc
const updated = await manager.updateBlock('block-guid', {
  blockTitle: 'Titre mis à jour',
  isDisabled: false
});

// Supprimer un bloc
const deleted = await manager.deleteBlock('block-guid');

Python

import requests

TENANT_ID = '12345678-1234-1234-1234-123456789012'
PROJECT_ID = '87654321-4321-4321-4321-210987654321'
BASE_URL = 'https://your-mindzie-instance.com'

class BlockManager:
    def __init__(self, token):
        self.headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }

    def get_block(self, block_id):
        """Obtenir les détails d'un bloc."""
        url = f'{BASE_URL}/api/{TENANT_ID}/{PROJECT_ID}/block/{block_id}'
        response = requests.get(url, headers=self.headers)

        if response.ok:
            return response.json()
        elif response.status_code == 404:
            raise Exception('Bloc introuvable')
        else:
            raise Exception(f'Échec de l\'obtention du bloc : {response.status_code}')

    def update_block(self, block_id, title=None, description=None, disabled=None):
        """Mettre à jour les métadonnées d'un bloc."""
        url = f'{BASE_URL}/api/{TENANT_ID}/{PROJECT_ID}/block/{block_id}'
        payload = {}
        if title is not None:
            payload['blockTitle'] = title
        if description is not None:
            payload['blockDescription'] = description
        if disabled is not None:
            payload['isDisabled'] = disabled

        response = requests.put(url, json=payload, headers=self.headers)

        if response.ok:
            return response.json()
        else:
            raise Exception(f'Échec de la mise à jour du bloc : {response.status_code}')

    def delete_block(self, block_id):
        """Supprimer un bloc."""
        url = f'{BASE_URL}/api/{TENANT_ID}/{PROJECT_ID}/block/{block_id}'
        response = requests.delete(url, headers=self.headers)
        return response.status_code == 204

# Utilisation
manager = BlockManager('your-auth-token')

# Obtenir un bloc
block = manager.get_block('block-guid')
print(f"Bloc : {block['blockTitle']} ({block['blockType']})")
print(f"Nombre d'exécutions : {block['executionCount']}")

# Mettre à jour un bloc
updated = manager.update_block('block-guid', title='Nouveau Titre', disabled=False)
print(f"Mis à jour : {updated['blockTitle']}")

# Supprimer un bloc
if manager.delete_block('block-guid'):
    print('Bloc supprimé avec succès')

C#

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

public class BlockReturn
{
    public Guid BlockId { get; set; }
    public Guid NotebookId { get; set; }
    public string BlockType { get; set; }
    public string BlockTitle { get; set; }
    public string BlockDescription { get; set; }
    public int BlockOrder { get; set; }
    public string Configuration { get; set; }
    public bool IsDisabled { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
    public string CreatedBy { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime? LastExecutionDate { get; set; }
    public string LastExecutionStatus { get; set; }
    public int ExecutionCount { get; set; }
}

public class BlockApiClient
{
    private readonly HttpClient _httpClient;
    private readonly string _baseUrl;
    private readonly Guid _tenantId;
    private readonly Guid _projectId;

    public BlockApiClient(string baseUrl, Guid tenantId, Guid projectId, string accessToken)
    {
        _baseUrl = baseUrl;
        _tenantId = tenantId;
        _projectId = projectId;
        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
    }

    public async Task<BlockReturn> GetBlockAsync(Guid blockId)
    {
        var url = $"{_baseUrl}/api/{_tenantId}/{_projectId}/block/{blockId}";
        var response = await _httpClient.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<BlockReturn>(json,
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
        }

        throw new Exception($"Échec de l'obtention du bloc : {response.StatusCode}");
    }

    public async Task<BlockReturn> UpdateBlockAsync(Guid blockId, string title, string description, bool? isDisabled)
    {
        var url = $"{_baseUrl}/api/{_tenantId}/{_projectId}/block/{blockId}";
        var payload = new
        {
            blockTitle = title,
            blockDescription = description,
            isDisabled = isDisabled
        };

        var content = new StringContent(
            JsonSerializer.Serialize(payload),
            Encoding.UTF8,
            "application/json");

        var response = await _httpClient.PutAsync(url, content);

        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<BlockReturn>(json,
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
        }

        throw new Exception($"Échec de la mise à jour du bloc : {response.StatusCode}");
    }

    public async Task<bool> DeleteBlockAsync(Guid blockId)
    {
        var url = $"{_baseUrl}/api/{_tenantId}/{_projectId}/block/{blockId}";
        var response = await _httpClient.DeleteAsync(url);
        return response.StatusCode == System.Net.HttpStatusCode.NoContent;
    }
}