API Dokumentation

Vollständige Referenz für die EIC-X Code Validation API

Schnellstart

Integrieren Sie die EIC-X Validation API in wenigen Minuten.

1. API-Key erhalten

Registrieren Sie sich unter eicxcode.ch/signup und generieren Sie Ihren API-Key im Dashboard.

2. Erste Anfrage

javascript
// Installation
// npm install axios (or use fetch)

// Single validation
async function validateCode(code) {
  try {
    const response = await fetch('https://api.eicxcode.ch/api/v1/validate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
      },
      body: JSON.stringify({ code })
    });

    const data = await response.json();
    
    if (data.valid) {
      console.log('Valid code:', data.normalized);
      console.log('Entity:', data.name);
      console.log('Company:', data.company);
    } else {
      console.log('Invalid code');
    }
    
    return data;
  } catch (error) {
    console.error('API Error:', error);
    throw error;
  }
}

// Usage
validateCode('12X-0000000002-J');

3. Response verarbeiten

json
{
  "valid": true,
  "normalized": "12X-0000000002-J",
  "name": "Swissgrid AG",
  "function": "TSO",
  "company": "Swissgrid AG",
  "zip": "5001",
  "city": "Aarau",
  "date": "2020-01-01",
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "duration": "45ms"
}

Feld-Beschreibungen:

  • valid: Boolean - Gibt an, ob der Code gültig ist
  • normalized: String - Normierte Version des Codes
  • name: String - Name der Entität
  • function: String - Funktion (TSO, DSO, SUP, MSP)
  • company: String - Firmenname
  • zip: String - Postleitzahl
  • city: String - Ort
  • date: String - Registrierungsdatum (ISO 8601)

Authentifizierung

Die EIC-X Validation API verwendet API-Key-basierte Authentifizierung über HTTP Header.

API-Key Header

Fügen Sie Ihren API-Key als Bearer Token im Authorization Header hinzu:

text
Authorization: Bearer YOUR_API_KEY

Beispiel Request

bash
curl -X POST https://api.eicxcode.ch/api/v1/validate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk_live_1234567890abcdef" \
  -d '{"code": "12X-0000000002-J"}'
Sicherheitshinweise
  • Niemals API-Keys im Frontend-Code oder öffentlichen Repositories speichern
  • API-Keys sollten nur auf dem Server verwendet werden
  • Bei Kompromittierung sofort einen neuen Key generieren
  • Verwenden Sie unterschiedliche Keys für Development und Production

Rate Limits

Rate Limits schützen die API vor Missbrauch und gewährleisten faire Nutzung für alle.

Standard Limits
Free Tier:100 Requests/Tag
Pro Tier:10,000 Requests/Tag
Enterprise:Unbegrenzt

Rate Limit Headers

Die API sendet Rate Limit Informationen in den Response Headers:

text
X-RateLimit-Limit: 10000
X-RateLimit-Remaining: 9995
X-RateLimit-Reset: 1642680000
Rate Limit Exceeded

Bei Überschreitung erhalten Sie einen 429 Too Many Requests Status.

json
{
  "error": "Rate limit exceeded",
  "retryAfter": 3600
}

POST /v1/validate

Validiert einen einzelnen EIC-X Code und gibt detaillierte Informationen zurück.

Request

Endpoint:

https://api.eicxcode.ch/api/v1/validate

Method:

POST

Content-Type:

application/json

Headers

HeaderRequiredDescription
AuthorizationOptionalBearer YOUR_API_KEY
Content-TypeRequiredapplication/json

Body Parameters

ParameterTypeRequiredDescription
codestringYesDer zu validierende EIC-X Code

Beispiel Request

javascript
// Installation
// npm install axios (or use fetch)

// Single validation
async function validateCode(code) {
  try {
    const response = await fetch('https://api.eicxcode.ch/api/v1/validate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
      },
      body: JSON.stringify({ code })
    });

    const data = await response.json();
    
    if (data.valid) {
      console.log('Valid code:', data.normalized);
      console.log('Entity:', data.name);
      console.log('Company:', data.company);
    } else {
      console.log('Invalid code');
    }
    
    return data;
  } catch (error) {
    console.error('API Error:', error);
    throw error;
  }
}

// Usage
validateCode('12X-0000000002-J');

Response

json
{
  "valid": true,
  "normalized": "12X-0000000002-J",
  "name": "Swissgrid AG",
  "function": "TSO",
  "company": "Swissgrid AG",
  "zip": "5001",
  "city": "Aarau",
  "date": "2020-01-01",
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "duration": "45ms"
}

POST /v1/validate (Batch)

Validiert mehrere EIC-X Codes in einer einzigen Anfrage. Maximale Anzahl: 100 Codes pro Request.

Body Parameters

ParameterTypeRequiredDescription
codesstring[]YesArray von EIC-X Codes (max. 100)

Beispiel Request

javascript
// Batch validation
async function validateCodes(codes) {
  try {
    const response = await fetch('https://api.eicxcode.ch/api/v1/validate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
      },
      body: JSON.stringify({ codes })
    });

    const data = await response.json();
    
    console.log(`Validated ${data.count} codes`);
    console.log(`${data.validCount} valid codes`);
    
    data.results.forEach(result => {
      if (result.valid) {
        console.log(`${result.code}: ${result.name}`);
      }
    });
    
    return data;
  } catch (error) {
    console.error('API Error:', error);
    throw error;
  }
}

// Usage
validateCodes(['12X-0000000002-J', '12X-0000000003-K']);

Response

json
{
  "results": [
    {
      "code": "12X-0000000002-J",
      "valid": true,
      "normalized": "12X-0000000002-J",
      "name": "Swissgrid AG",
      "function": "TSO",
      "company": "Swissgrid AG"
    },
    {
      "code": "12X-0000000003-K",
      "valid": false,
      "normalized": "12X-0000000003-K",
      "message": "EIC-X code not found in database"
    }
  ],
  "count": 2,
  "validCount": 1,
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "duration": "120ms"
}

GET /v1/validate

Alternative GET-Methode für einfache Validierungen ohne Authentifizierung (nur für Testing).

Query Parameters

ParameterTypeRequiredDescription
codestringYesDer zu validierende EIC-X Code

Beispiel Request

javascript
// GET request (simpler, no auth required for testing)
async function validateCodeGet(code) {
  try {
    const response = await fetch(
      `https://api.eicxcode.ch/api/v1/validate?code=${encodeURIComponent(code)}`
    );
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('API Error:', error);
    throw error;
  }
}

// Usage
validateCodeGet('12X-0000000002-J');

Success Response

Bei erfolgreicher Validierung erhalten Sie detaillierte Informationen über den EIC-X Code.

json
{
  "valid": true,
  "normalized": "12X-0000000002-J",
  "name": "Swissgrid AG",
  "function": "TSO",
  "company": "Swissgrid AG",
  "zip": "5001",
  "city": "Aarau",
  "date": "2020-01-01",
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "duration": "45ms"
}

Error Handling

Die API verwendet standardisierte Error-Responses mit aussagekräftigen Fehlermeldungen.

Error Response Format

json
{
  "valid": false,
  "error": "Invalid EIC-X code format",
  "requestId": "550e8400-e29b-41d4-a716-446655440000"
}

Häufige Fehler

400 Bad Request

Ungültige Anfrage:

json
{
  "valid": false,
  "error": "Missing code parameter",
  "requestId": "..."
}
429 Too Many Requests

Rate Limit überschritten:

json
{
  "error": "Rate limit exceeded",
  "retryAfter": 3600
}
500 Internal Server Error

Server-Fehler:

json
{
  "valid": false,
  "error": "Unknown error occurred",
  "requestId": "..."
}

Status Codes

Status CodeDescription
200Erfolgreiche Anfrage
400Ungültige Anfrage (fehlende/ungültige Parameter)
401Unauthorized (ungültiger API-Key)
429Rate Limit überschritten
500Interner Server-Fehler

Code Examples

Vollständige, funktionsfähige Beispiele für verschiedene Programmiersprachen.

JavaScript/TypeScript

javascript
// Installation
// npm install axios (or use fetch)

// Single validation
async function validateCode(code) {
  try {
    const response = await fetch('https://api.eicxcode.ch/api/v1/validate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
      },
      body: JSON.stringify({ code })
    });

    const data = await response.json();
    
    if (data.valid) {
      console.log('Valid code:', data.normalized);
      console.log('Entity:', data.name);
      console.log('Company:', data.company);
    } else {
      console.log('Invalid code');
    }
    
    return data;
  } catch (error) {
    console.error('API Error:', error);
    throw error;
  }
}

// Usage
validateCode('12X-0000000002-J');

Python

python
# Installation
# pip install requests

import requests

def validate_code(code):
    """Validate a single EIC-X code"""
    url = 'https://api.eicxcode.ch/api/v1/validate'
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY'
    }
    payload = {'code': code}
    
    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()
        data = response.json()
        
        if data.get('valid'):
            print(f"Valid code: {data['normalized']}")
            print(f"Entity: {data['name']}")
            print(f"Company: {data['company']}")
        else:
            print("Invalid code")
        
        return data
    except requests.exceptions.RequestException as e:
        print(f"API Error: {e}")
        raise

# Usage
validate_code('12X-0000000002-J')

cURL

bash
# Single validation
curl -X POST https://api.eicxcode.ch/api/v1/validate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "code": "12X-0000000002-J"
  }'

Go

go
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

type ValidateRequest struct {
    Code string `json:"code"`
}

type ValidateResponse struct {
    Valid      bool   `json:"valid"`
    Normalized string `json:"normalized"`
    Name       string `json:"name,omitempty"`
    Company    string `json:"company,omitempty"`
    Function   string `json:"function,omitempty"`
    Zip        string `json:"zip,omitempty"`
    City       string `json:"city,omitempty"`
    Date       string `json:"date,omitempty"`
}

func validateCode(code string) (*ValidateResponse, error) {
    url := "https://api.eicxcode.ch/api/v1/validate"
    
    reqBody := ValidateRequest{Code: code}
    jsonData, err := json.Marshal(reqBody)
    if err != nil {
        return nil, err
    }
    
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        return nil, err
    }
    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    
    var result ValidateResponse
    if err := json.Unmarshal(body, &result); err != nil {
        return nil, err
    }
    
    return &result, nil
}

func main() {
    result, err := validateCode("12X-0000000002-J")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    if result.Valid {
        fmt.Printf("Valid code: %s\n", result.Normalized)
        fmt.Printf("Entity: %s\n", result.Name)
    } else {
        fmt.Println("Invalid code")
    }
}

Best Practices

Fehlerbehandlung

  • Implementieren Sie Retry-Logik mit exponential backoff
  • Behandeln Sie Rate Limit Errors (429) mit entsprechenden Wartezeiten
  • Loggen Sie API-Fehler für Debugging und Monitoring
  • Validieren Sie Eingaben vor dem API-Call
javascript
// Beispiel: Retry-Logik mit exponential backoff
async function validateWithRetry(code, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch('https://api.eicxcode.ch/api/v1/validate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer YOUR_API_KEY'
        },
        body: JSON.stringify({ code })
      });

      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }

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

      return await response.json();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
    }
  }
}

Caching-Strategien

  • Cachen Sie erfolgreiche Validierungen (TTL: 24h)
  • Nutzen Sie ETag/If-None-Match Headers wenn verfügbar
  • Vermeiden Sie unnötige Re-Validierungen
  • Implementieren Sie Cache-Invalidation bei Bedarf
javascript
// Beispiel: Caching mit localStorage (Browser)
const CACHE_TTL = 24 * 60 * 60 * 1000; // 24 Stunden

async function validateWithCache(code) {
  const cacheKey = `eicx_${code}`;
  const cached = localStorage.getItem(cacheKey);
  
  if (cached) {
    const { data, timestamp } = JSON.parse(cached);
    if (Date.now() - timestamp < CACHE_TTL) {
      return data;
    }
  }
  
  const data = await validateCode(code);
  localStorage.setItem(cacheKey, JSON.stringify({
    data,
    timestamp: Date.now()
  }));
  
  return data;
}

Performance-Tipps

  • Nutzen Sie Batch-Endpoint für mehrere Codes
  • Vermeiden Sie parallele Requests (Rate Limit beachten)
  • Implementieren Sie Request-Queuing für große Mengen
  • Nutzen Sie GET-Endpoint für einfache Validierungen ohne Auth
javascript
// Beispiel: Batch-Validierung statt einzelner Requests
async function validateMultipleCodes(codes) {
  // ❌ Schlecht: Viele einzelne Requests
  // const results = await Promise.all(
  //   codes.map(code => validateCode(code))
  // );
  
  // ✅ Gut: Ein Batch-Request
  const response = await fetch('https://api.eicxcode.ch/api/v1/validate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify({ codes })
  });
  
  const data = await response.json();
  return data.results;
}

Support

Benötigen Sie Hilfe? Wir sind für Sie da.

Kontakt

E-Mail: support@eicxcode.ch

Antwortzeit: Innerhalb von 24 Stunden (Mo-Fr)

Status Page

API-Status und Uptime-Informationen

Status anzeigen
Response-Zeit-Garantien
Free Tier:< 1000ms (95. Perzentil)
Pro Tier:< 500ms (95. Perzentil)
Enterprise:< 300ms (95. Perzentil)
GitHub

Issues, Discussions und Code-Beispiele

GitHub öffnen

FAQ

Wie erhalte ich einen API-Key?

Registrieren Sie sich auf eicxcode.ch und generieren Sie Ihren API-Key im Dashboard unter "API Keys".

Gibt es ein Limit für Batch-Requests?

Ja, Sie können maximal 100 Codes pro Batch-Request validieren. Für größere Mengen teilen Sie die Codes in mehrere Batches auf.

Ist die API kostenlos?

Wir bieten einen kostenlosen Tier mit 100 Requests pro Tag. Für höhere Limits und zusätzliche Features stehen Pro- und Enterprise-Pläne zur Verfügung.

Wie aktuell sind die Daten?

Die EIC-X Code-Datenbank wird täglich aktualisiert und enthält alle registrierten Codes aus der Swissgrid-Datenbank.