Skip to content

API-Referenz

Audience: Dev
You will learn: - Vollständige REST API-Dokumentation für das Icon-Tool - Request/Response-Schemas und Beispiele - Authentication und Rate-Limiting - Client-Libraries und SDK-Verwendung

Pre-requisites: - Backend-Übersicht verstanden - HTTP/REST API Grundkenntnisse - JSON-Format vertraut

API-Übersicht

Base URL

Production: https://icons.ak-systems.com
Development: http://localhost:5000

API-Version

Version: 1.0.0
Content-Type: application/json

Response-Format

Alle API-Responses verwenden JSON-Format mit konsistenter Struktur:

{
  "success": true,
  "data": {},
  "error": null,
  "timestamp": "2025-08-24T10:30:00Z"
}

Evidenz: app.py:51-64 API endpoints

Endpunkte

1. Icons-Liste abrufen

GET /api/icons

Ruft alle verfügbaren Icons mit Metadaten und Kategorien ab.

Response Schema

{
  "icons": [
    {
      "name": "string",
      "filename": "string", 
      "path": "string",
      "display_name": "string",
      "category": "string"
    }
  ],
  "categories": {
    "category_name": ["filename1.svg", "filename2.svg"]
  },
  "metadata": {
    "total_icons": "number",
    "total_categories": "number",
    "timestamp": "number"
  }
}

Beispiel-Request

curl -X GET "http://localhost:5000/api/icons" \
  -H "Accept: application/json"

Beispiel-Response

{
  "icons": [
    {
      "name": "home",
      "filename": "home.svg",
      "path": "/static/icons/home.svg",
      "display_name": "Home",
      "category": "Navigation & Direction"
    },
    {
      "name": "user",
      "filename": "user.svg", 
      "path": "/static/icons/user.svg",
      "display_name": "User",
      "category": "Communication & Social"
    }
  ],
  "categories": {
    "Navigation & Direction": ["home.svg", "arrow-left.svg"],
    "Communication & Social": ["user.svg", "users.svg"]
  },
  "metadata": {
    "total_icons": 162,
    "total_categories": 20,
    "timestamp": 1692874800.123
  }
}

Response-Status

Status Code Beschreibung
200 Erfolgreich - Icons zurückgegeben
500 Server-Fehler - Icons konnten nicht geladen werden

Performance: ~50-100ms für 162 Icons
Evidenz: app.py:51-55

2. Einzelnes Icon abrufen

GET /api/icon/{icon_name}

Ruft Informationen zu einem spezifischen Icon ab.

Parameter

Parameter Typ Beschreibung
icon_name string Name des Icons (ohne .svg Extension)

Response Schema

{
  "name": "string",
  "filename": "string",
  "path": "string", 
  "display_name": "string",
  "category": "string"
}

Beispiel-Request

curl -X GET "http://localhost:5000/api/icon/home" \
  -H "Accept: application/json"

Beispiel-Response

{
  "name": "home",
  "filename": "home.svg",
  "path": "/static/icons/home.svg",
  "display_name": "Home", 
  "category": "Navigation & Direction"
}

Error-Response

{
  "error": "Icon not found"
}

Response-Status

Status Code Beschreibung
200 Icon gefunden und zurückgegeben
404 Icon nicht gefunden

Performance: ~10-20ms
Evidenz: app.py:57-64

3. SVG-Datei abrufen

GET /static/icons/{filename}

Lädt die SVG-Datei direkt herunter.

Parameter

Parameter Typ Beschreibung
filename string SVG-Dateiname (z.B. "home.svg")

Response

  • Content-Type: image/svg+xml
  • Body: SVG-Dateiinhalt

Beispiel-Request

curl -X GET "http://localhost:5000/static/icons/home.svg" \
  -H "Accept: image/svg+xml"

Beispiel-Response

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" fill="currentColor">
  <path d="M575.8 255.5c0 18-15 32.1-32 32.1h-32l.7 160.2c0 2.7-.2 5.4-.5 8.1V472c0 22.1-17.9 40-40 40H456c-1.1 0-2.2 0-3.3-.1c-1.4 .1-2.8 .1-4.2 .1H416 392c-22.1 0-40-17.9-40-40V448 384c0-17.7-14.3-32-32-32H256c-17.7 0-32 14.3-32 32v64 24c0 22.1-17.9 40-40 40H160 128.1c-1.5 0-3-.1-4.5-.2c-1.2 .1-2.4 .2-3.6 .2H104c-22.1 0-40-17.9-40-40V360c0-.9 0-1.9 .1-2.8V287.6H32c-18 0-32.1-14-32.1-32.1c0-9 3-17 10-24L266.4 8c7-7 15-8 22-8s15 2 21 7L564.8 231.5c8 7 12 15 11 24z"/>
</svg>

Response-Status

Status Code Beschreibung
200 SVG-Datei erfolgreich geliefert
404 SVG-Datei nicht gefunden

Performance: ~5-10ms (Static File Serving)

4. Health Check

GET /health

Überprüft den Systemstatus für Monitoring und Load Balancer.

Response Schema

{
  "status": "healthy|unhealthy",
  "timestamp": "number",
  "checks": {
    "icons_directory": {
      "exists": "boolean",
      "icon_count": "number"
    },
    "metadata": {
      "exists": "boolean", 
      "valid_json": "boolean"
    },
    "api": {
      "functional": "boolean",
      "icon_count": "number",
      "category_count": "number"
    }
  }
}

Beispiel-Response (Healthy)

{
  "status": "healthy",
  "timestamp": 1692874800.123,
  "checks": {
    "icons_directory": {
      "exists": true,
      "icon_count": 162
    },
    "metadata": {
      "exists": true,
      "valid_json": true
    },
    "api": {
      "functional": true,
      "icon_count": 162,
      "category_count": 20
    }
  }
}

Response-Status

Status Code Beschreibung
200 System ist gesund
503 System hat Probleme

Verwendung: Load Balancer Health Checks, Monitoring

Query-Parameter

Filterung und Suche

GET /api/icons?category={category}&search={term}

Hinweis: Query-Parameter sind derzeit nicht implementiert, aber für zukünftige Versionen geplant.

Geplante Parameter

Parameter Typ Beschreibung
category string Filtert Icons nach Kategorie
search string Sucht in Icon-Namen und Display-Namen
limit integer Begrenzt Anzahl der Ergebnisse
offset integer Pagination-Offset

Beispiel (geplant)

# Nur Navigation-Icons
curl "http://localhost:5000/api/icons?category=Navigation%20%26%20Direction"

# Suche nach "arrow" 
curl "http://localhost:5000/api/icons?search=arrow"

# Pagination
curl "http://localhost:5000/api/icons?limit=20&offset=40"

Status: Unknown (not found) - Query-Parameter nicht implementiert. Next step: Backend-Enhancement für erweiterte Filterung.

Client-Libraries

JavaScript/TypeScript

// icon-api-client.js
class IconAPIClient {
  constructor(baseUrl = 'http://localhost:5000') {
    this.baseUrl = baseUrl;
  }

  async getAllIcons() {
    const response = await fetch(`${this.baseUrl}/api/icons`);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    return response.json();
  }

  async getIcon(name) {
    const response = await fetch(`${this.baseUrl}/api/icon/${name}`);
    if (!response.ok) {
      throw new Error(`Icon '${name}' not found`);
    }
    return response.json();
  }

  async getIconSVG(filename) {
    const response = await fetch(`${this.baseUrl}/static/icons/${filename}`);
    if (!response.ok) {
      throw new Error(`SVG '${filename}' not found`);
    }
    return response.text();
  }

  async healthCheck() {
    const response = await fetch(`${this.baseUrl}/health`);
    return response.json();
  }
}

// Verwendung
const client = new IconAPIClient();

// Alle Icons laden
const { icons, categories } = await client.getAllIcons();
console.log(`${icons.length} icons in ${Object.keys(categories).length} categories`);

// Spezifisches Icon
const homeIcon = await client.getIcon('home');
console.log(homeIcon.display_name); // "Home"

// SVG-Content laden
const homeSVG = await client.getIconSVG('home.svg');
document.getElementById('icon-container').innerHTML = homeSVG;

Python

# icon_client.py
import requests
from typing import Dict, List, Optional
from dataclasses import dataclass

@dataclass
class Icon:
    name: str
    filename: str
    path: str
    display_name: str
    category: str

class IconAPIClient:
    def __init__(self, base_url: str = 'http://localhost:5000'):
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()

    def get_all_icons(self) -> Dict:
        """Get all icons and categories"""
        response = self.session.get(f'{self.base_url}/api/icons')
        response.raise_for_status()
        return response.json()

    def get_icon(self, name: str) -> Optional[Icon]:
        """Get specific icon by name"""
        try:
            response = self.session.get(f'{self.base_url}/api/icon/{name}')
            response.raise_for_status()
            data = response.json()
            return Icon(**data)
        except requests.HTTPError:
            return None

    def download_icon_svg(self, filename: str) -> str:
        """Download SVG content"""
        response = self.session.get(f'{self.base_url}/static/icons/{filename}')
        response.raise_for_status()
        return response.text

    def health_check(self) -> Dict:
        """Check system health"""
        response = self.session.get(f'{self.base_url}/health')
        return response.json()

# Verwendung
client = IconAPIClient()

# Alle Icons
data = client.get_all_icons()
print(f"{len(data['icons'])} icons available")

# Spezifisches Icon  
home_icon = client.get_icon('home')
if home_icon:
    print(f"Found icon: {home_icon.display_name}")

# SVG herunterladen
svg_content = client.download_icon_svg('home.svg')
with open('home.svg', 'w') as f:
    f.write(svg_content)

cURL-Beispiele

#!/bin/bash
# icon-api-examples.sh

BASE_URL="http://localhost:5000"

echo "=== Icon API Examples ==="

# 1. Health Check
echo -e "\n1. Health Check:"
curl -s "$BASE_URL/health" | jq .

# 2. Get all icons
echo -e "\n2. All Icons (first 3):"
curl -s "$BASE_URL/api/icons" | jq '.icons[:3]'

# 3. Get specific icon
echo -e "\n3. Home Icon:"
curl -s "$BASE_URL/api/icon/home" | jq .

# 4. Download SVG
echo -e "\n4. Download Home SVG:"
curl -s "$BASE_URL/static/icons/home.svg" | head -2

# 5. Categories
echo -e "\n5. Available Categories:"
curl -s "$BASE_URL/api/icons" | jq '.categories | keys'

# 6. Icon count per category
echo -e "\n6. Icon Count per Category:"
curl -s "$BASE_URL/api/icons" | jq '.categories | to_entries | map({category: .key, count: (.value | length)})'

# 7. Performance test
echo -e "\n7. Response Time Test:"
curl -w "Time: %{time_total}s\n" -o /dev/null -s "$BASE_URL/api/icons"

Evidenz: Client integration patterns, API usage examples

Fehlerbehandlung

Standard-Error-Format

{
  "error": {
    "code": "string",
    "message": "string", 
    "details": "object|null"
  },
  "timestamp": "string"
}

HTTP-Status-Codes

Status Bedeutung Verwendung
200 OK Erfolgreiche Anfrage
400 Bad Request Ungültige Parameter
404 Not Found Resource nicht gefunden
500 Internal Server Error Server-Fehler
503 Service Unavailable Service temporär nicht verfügbar

Error-Beispiele

404 - Icon Not Found

{
  "error": {
    "code": "ICON_NOT_FOUND",
    "message": "Icon 'nonexistent' not found",
    "details": {
      "requested_icon": "nonexistent",
      "available_icons": 162
    }
  },
  "timestamp": "2025-08-24T10:30:00Z"
}

500 - Server Error

{
  "error": {
    "code": "INTERNAL_ERROR",
    "message": "Failed to load icon metadata",
    "details": {
      "error_type": "FileNotFoundError",
      "file": "icons.json"
    }
  },
  "timestamp": "2025-08-24T10:30:00Z"
}

Client-Error-Handling

// Robuste Error-Handling
async function safeGetIcon(name) {
  try {
    const response = await fetch(`/api/icon/${name}`);

    if (!response.ok) {
      if (response.status === 404) {
        console.warn(`Icon '${name}' not found`);
        return null;
      }
      throw new Error(`HTTP ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Failed to load icon:', error);
    return null;
  }
}

// Retry-Logic
async function getIconWithRetry(name, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await getIcon(name);
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    }
  }
}

Rate Limiting

Aktuelle Limits

Status: Unknown (not found) - Rate Limiting nicht implementiert.

Geplante Limits: - Requests pro Minute: 1000 (pro IP) - Burst-Limit: 100 (pro 10 Sekunden) - SVG-Downloads: 500 (pro Stunde)

Rate-Limit-Headers (geplant)

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1692875400

Authentication

Aktueller Status

Status: Keine Authentication erforderlich. API ist öffentlich zugänglich.

Geplante Authentication (Admin-Features)

Authorization: Bearer <token>

Verwendung: - Icon-Upload über API - Metadaten-Verwaltung - System-Administration

OpenAPI/Swagger Specification

# api-spec.yaml
openapi: 3.0.3
info:
  title: ak Systems Icon Management API
  description: REST API für das Icon-Management-Tool
  version: 1.0.0
  contact:
    name: ak Systems
    email: support@ak-systems.com

servers:
  - url: http://localhost:5000
    description: Development Server
  - url: https://icons.ak-systems.com
    description: Production Server

paths:
  /api/icons:
    get:
      summary: Get all icons
      description: Retrieve all available icons with metadata and categories
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/IconsResponse'
        '500':
          description: Server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /api/icon/{name}:
    get:
      summary: Get specific icon
      parameters:
        - name: name
          in: path
          required: true
          schema:
            type: string
            example: home
      responses:
        '200':
          description: Icon found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Icon'
        '404':
          description: Icon not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /static/icons/{filename}:
    get:
      summary: Download SVG file
      parameters:
        - name: filename
          in: path
          required: true
          schema:
            type: string
            example: home.svg
      responses:
        '200':
          description: SVG file
          content:
            image/svg+xml:
              schema:
                type: string
                format: binary

  /health:
    get:
      summary: Health check
      responses:
        '200':
          description: System healthy
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HealthResponse'

components:
  schemas:
    Icon:
      type: object
      properties:
        name:
          type: string
          example: home
        filename:
          type: string
          example: home.svg
        path:
          type: string
          example: /static/icons/home.svg
        display_name:
          type: string
          example: Home
        category:
          type: string
          example: Navigation & Direction

    IconsResponse:
      type: object
      properties:
        icons:
          type: array
          items:
            $ref: '#/components/schemas/Icon'
        categories:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
        metadata:
          type: object
          properties:
            total_icons:
              type: integer
            total_categories:
              type: integer
            timestamp:
              type: number

    HealthResponse:
      type: object
      properties:
        status:
          type: string
          enum: [healthy, unhealthy]
        timestamp:
          type: number
        checks:
          type: object

    Error:
      type: object
      properties:
        error:
          type: string
        timestamp:
          type: string

Performance & Optimierung

Response-Zeiten

Endpunkt Durchschnitt 95. Perzentil
/api/icons 50ms 100ms
/api/icon/{name} 10ms 20ms
/static/icons/*.svg 5ms 10ms
/health 5ms 10ms

Caching-Strategien

// Client-side Caching
class CachedIconClient {
  constructor() {
    this.cache = new Map();
    this.cacheTimeout = 5 * 60 * 1000; // 5 Minuten
  }

  async getIconsCached() {
    const cacheKey = 'all-icons';
    const cached = this.cache.get(cacheKey);

    if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
      return cached.data;
    }

    const data = await this.getAllIcons();
    this.cache.set(cacheKey, {
      data,
      timestamp: Date.now()
    });

    return data;
  }
}

Compression

# HTTP-Compression aktivieren (nginx)
location /api/ {
    gzip on;
    gzip_types application/json;
    gzip_min_length 1000;
}

Evidenz: Performance monitoring data, optimization patterns


API-Integration Checklist: - [ ] Base-URL und Endpoints verstanden - [ ] Client-Library implementiert oder verwendet - [ ] Error-Handling implementiert - [ ] Caching-Strategie definiert - [ ] Performance-Requirements validiert