Code-Beispiele
Diese Sammlung von Code-Beispielen zeigt Ihnen, wie Sie die MILKEE API in verschiedenen Programmiersprachen verwenden können.
Schnellstart
Voraussetzungen
- API-Token: Erstellen Sie einen API-Token in Ihren MILKEE-Einstellungen
- Firmen-ID: Ermitteln Sie Ihre Firmen-ID aus der MILKEE-URL oder via
/users/me
- HTTPS: Alle Requests müssen über HTTPS erfolgen
Base-Konfiguration
Alle Beispiele verwenden folgende Konfiguration:
Base URL: https://app.milkee.ch/api/v2
Firmen-ID: 123 (ersetzen Sie dies mit Ihrer eigenen ID)
Token: abcdef123456789... (ersetzen Sie dies mit Ihrem Token)
JavaScript/Fetch
API-Client Klasse
javascript
class MilkeeAPI {
constructor(token, companyId) {
this.token = token;
this.companyId = companyId;
this.baseURL = 'https://app.milkee.ch/api/v2';
}
async request(endpoint, options = {}) {
const url = `${this.baseURL}/companies/${this.companyId}${endpoint}`;
const config = {
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
...options.headers
},
...options
};
if (options.body && typeof options.body === 'object') {
config.body = JSON.stringify(options.body);
}
const response = await fetch(url, config);
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error (${response.status}): ${error.message}`);
}
return response.json();
}
// Tags-Methoden
async getTags(page = 1, perPage = 15) {
return this.request(`/tags?page=${page}&per_page=${perPage}`);
}
async getTag(tagId) {
return this.request(`/tags/${tagId}`);
}
async createTag(tagData) {
return this.request('/tags', {
method: 'POST',
body: tagData
});
}
async updateTag(tagId, tagData) {
return this.request(`/tags/${tagId}`, {
method: 'PUT',
body: tagData
});
}
async deleteTag(tagId) {
return this.request(`/tags/${tagId}`, {
method: 'DELETE'
});
}
async getTagColors() {
return this.request('/tags/colors');
}
}
// Verwendung
const api = new MilkeeAPI('abcdef123456789...', 123);
// Alle Tags abrufen
const tags = await api.getTags();
console.log('Tags:', tags.data);
// Neuen Tag erstellen
const newTag = await api.createTag({
name: 'marketing-ausgaben',
color: 'purple'
});
console.log('Neuer Tag:', newTag);
// Tag aktualisieren
const updatedTag = await api.updateTag(newTag.id, {
name: 'marketing-kosten',
color: 'red'
});
console.log('Aktualisierter Tag:', updatedTag);
// Tag löschen
await api.deleteTag(newTag.id);
console.log('Tag gelöscht');
Async/Await mit Fehlerbehandlung
javascript
async function handleTagOperations() {
const api = new MilkeeAPI('abcdef123456789...', 123);
try {
// Verfügbare Farben abrufen
const colors = await api.getTagColors();
console.log('Verfügbare Farben:', colors);
// Tag erstellen
const tag = await api.createTag({
name: 'neue-kategorie',
color: colors[0] // Erste verfügbare Farbe verwenden
});
console.log('Tag erstellt:', tag);
// Tag sofort wieder aktualisieren
const updatedTag = await api.updateTag(tag.id, {
name: 'aktualisierte-kategorie',
color: 'blue'
});
console.log('Tag aktualisiert:', updatedTag);
} catch (error) {
if (error.message.includes('422')) {
console.error('Validierungsfehler:', error.message);
} else if (error.message.includes('401')) {
console.error('Authentifizierung fehlgeschlagen - Token prüfen');
} else if (error.message.includes('402')) {
console.error('Abonnement abgelaufen - Business Plan erforderlich');
} else {
console.error('Allgemeiner Fehler:', error.message);
}
}
}
handleTagOperations();
PHP/cURL
API-Client Klasse
php
<?php
class MilkeeAPI {
private $token;
private $companyId;
private $baseURL = 'https://app.milkee.ch/api/v2';
public function __construct($token, $companyId) {
$this->token = $token;
$this->companyId = $companyId;
}
private function request($endpoint, $method = 'GET', $data = null) {
$url = $this->baseURL . "/companies/{$this->companyId}" . $endpoint;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->token,
'Content-Type: application/json'
]);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} elseif ($method === 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} elseif ($method === 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$decodedResponse = json_decode($response, true);
if ($httpCode >= 400) {
$message = $decodedResponse['message'] ?? 'Unknown error';
throw new Exception("API Error ({$httpCode}): {$message}");
}
return $decodedResponse;
}
// Tags-Methoden
public function getTags($page = 1, $perPage = 15) {
return $this->request("/tags?page={$page}&per_page={$perPage}");
}
public function getTag($tagId) {
return $this->request("/tags/{$tagId}");
}
public function createTag($tagData) {
return $this->request('/tags', 'POST', $tagData);
}
public function updateTag($tagId, $tagData) {
return $this->request("/tags/{$tagId}", 'PUT', $tagData);
}
public function deleteTag($tagId) {
return $this->request("/tags/{$tagId}", 'DELETE');
}
public function getTagColors() {
return $this->request('/tags/colors');
}
}
// Verwendung
try {
$api = new MilkeeAPI('abcdef123456789...', 123);
// Alle Tags abrufen
$tags = $api->getTags();
echo "Tags gefunden: " . count($tags['data']) . "\n";
// Neuen Tag erstellen
$newTag = $api->createTag([
'name' => 'php-beispiel',
'color' => 'green'
]);
echo "Neuer Tag erstellt: {$newTag['name']} (ID: {$newTag['id']})\n";
// Tag aktualisieren
$updatedTag = $api->updateTag($newTag['id'], [
'name' => 'php-beispiel-aktualisiert',
'color' => 'blue'
]);
echo "Tag aktualisiert: {$updatedTag['name']}\n";
// Verfügbare Farben abrufen
$colors = $api->getTagColors();
echo "Verfügbare Farben: " . implode(', ', $colors) . "\n";
// Tag löschen
$api->deleteTag($newTag['id']);
echo "Tag gelöscht\n";
} catch (Exception $e) {
echo "Fehler: " . $e->getMessage() . "\n";
}
Laravel HTTP Client (für Laravel-Projekte)
php
<?php
use Illuminate\Support\Facades\Http;
class MilkeeAPIService {
private $token;
private $companyId;
private $baseURL = 'https://app.milkee.ch/api/v2';
public function __construct($token, $companyId) {
$this->token = $token;
$this->companyId = $companyId;
}
private function getClient() {
return Http::withHeaders([
'Authorization' => "Bearer {$this->token}",
'Content-Type' => 'application/json'
])->baseUrl($this->baseURL);
}
public function getTags($page = 1, $perPage = 15) {
$response = $this->getClient()->get(
"/companies/{$this->companyId}/tags",
compact('page', 'perPage')
);
$response->throw(); // Wirft Exception bei HTTP-Fehlern
return $response->json();
}
public function createTag(array $tagData) {
$response = $this->getClient()->post(
"/companies/{$this->companyId}/tags",
$tagData
);
$response->throw();
return $response->json();
}
public function updateTag($tagId, array $tagData) {
$response = $this->getClient()->put(
"/companies/{$this->companyId}/tags/{$tagId}",
$tagData
);
$response->throw();
return $response->json();
}
public function deleteTag($tagId) {
$response = $this->getClient()->delete(
"/companies/{$this->companyId}/tags/{$tagId}"
);
$response->throw();
return $response->json();
}
}
// Verwendung in Laravel Controller
class TagController extends Controller {
public function syncTags() {
$milkeeAPI = new MilkeeAPIService(
config('milkee.api_token'),
config('milkee.company_id')
);
try {
$tags = $milkeeAPI->getTags();
// Tags in lokaler Datenbank synchronisieren
foreach ($tags['data'] as $tagData) {
Tag::updateOrCreate(
['milkee_id' => $tagData['id']],
[
'name' => $tagData['name'],
'color' => $tagData['color']
]
);
}
return response()->json(['message' => 'Tags synchronized']);
} catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
}
Python/Requests
API-Client Klasse
python
import requests
import json
from typing import Optional, Dict, Any, List
class MilkeeAPI:
def __init__(self, token: str, company_id: int):
self.token = token
self.company_id = company_id
self.base_url = 'https://app.milkee.ch/api/v2'
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
})
def _request(self, endpoint: str, method: str = 'GET', data: Optional[Dict] = None) -> Dict[Any, Any]:
url = f"{self.base_url}/companies/{self.company_id}{endpoint}"
try:
if method == 'GET':
response = self.session.get(url)
elif method == 'POST':
response = self.session.post(url, json=data)
elif method == 'PUT':
response = self.session.put(url, json=data)
elif method == 'DELETE':
response = self.session.delete(url)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
error_data = response.json() if response.content else {}
error_message = error_data.get('message', str(e))
raise Exception(f"API Error ({response.status_code}): {error_message}")
# Tags-Methoden
def get_tags(self, page: int = 1, per_page: int = 15) -> Dict[str, Any]:
return self._request(f"/tags?page={page}&per_page={per_page}")
def get_tag(self, tag_id: int) -> Dict[str, Any]:
return self._request(f"/tags/{tag_id}")
def create_tag(self, tag_data: Dict[str, str]) -> Dict[str, Any]:
return self._request("/tags", "POST", tag_data)
def update_tag(self, tag_id: int, tag_data: Dict[str, str]) -> Dict[str, Any]:
return self._request(f"/tags/{tag_id}", "PUT", tag_data)
def delete_tag(self, tag_id: int) -> Dict[str, Any]:
return self._request(f"/tags/{tag_id}", "DELETE")
def get_tag_colors(self) -> List[str]:
return self._request("/tags/colors")
def get_all_tags(self) -> List[Dict[str, Any]]:
"""Ruft alle Tags ab (über alle Seiten hinweg)"""
all_tags = []
page = 1
while True:
response = self.get_tags(page=page, per_page=100)
all_tags.extend(response['data'])
if response['meta']['current_page'] >= response['meta']['last_page']:
break
page += 1
return all_tags
# Verwendung
def main():
api = MilkeeAPI('abcdef123456789...', 123)
try:
# Verfügbare Farben abrufen
colors = api.get_tag_colors()
print(f"Verfügbare Farben: {', '.join(colors)}")
# Neuen Tag erstellen
new_tag = api.create_tag({
'name': 'python-beispiel',
'color': colors[0] # Erste verfügbare Farbe
})
print(f"Tag erstellt: {new_tag['name']} (ID: {new_tag['id']})")
# Tag aktualisieren
updated_tag = api.update_tag(new_tag['id'], {
'name': 'python-beispiel-aktualisiert',
'color': 'blue'
})
print(f"Tag aktualisiert: {updated_tag['name']}")
# Alle Tags abrufen
all_tags = api.get_all_tags()
print(f"Insgesamt {len(all_tags)} Tags gefunden")
# Tag löschen
api.delete_tag(new_tag['id'])
print("Tag gelöscht")
except Exception as e:
print(f"Fehler: {e}")
if __name__ == "__main__":
main()
Django Integration
python
# models.py
from django.db import models
class MilkeeTag(models.Model):
milkee_id = models.IntegerField(unique=True)
name = models.CharField(max_length=255)
color = models.CharField(max_length=50)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
# management/commands/sync_milkee_tags.py
from django.core.management.base import BaseCommand
from django.conf import settings
from myapp.models import MilkeeTag
from myapp.services import MilkeeAPI
class Command(BaseCommand):
help = 'Synchronisiert Tags von MILKEE API'
def handle(self, *args, **options):
api = MilkeeAPI(
settings.MILKEE_API_TOKEN,
settings.MILKEE_COMPANY_ID
)
try:
tags = api.get_all_tags()
for tag_data in tags:
tag, created = MilkeeTag.objects.update_or_create(
milkee_id=tag_data['id'],
defaults={
'name': tag_data['name'],
'color': tag_data['color']
}
)
action = "erstellt" if created else "aktualisiert"
self.stdout.write(f"Tag '{tag.name}' {action}")
self.stdout.write(
self.style.SUCCESS(f'{len(tags)} Tags synchronisiert')
)
except Exception as e:
self.stdout.write(
self.style.ERROR(f'Fehler bei Synchronisation: {e}')
)
cURL-Kommandos
Grundlegende Operationen
bash
# API-Token und Firmen-ID setzen
export MILKEE_TOKEN="abcdef123456789..."
export MILKEE_COMPANY="123"
export API_BASE="https://app.milkee.ch/api/v2"
# Alle Tags abrufen
curl -H "Authorization: Bearer $MILKEE_TOKEN" \
"$API_BASE/companies/$MILKEE_COMPANY/tags"
# Verfügbare Farben abrufen
curl -H "Authorization: Bearer $MILKEE_TOKEN" \
"$API_BASE/companies/$MILKEE_COMPANY/tags/colors"
# Neuen Tag erstellen
curl -X POST \
-H "Authorization: Bearer $MILKEE_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"curl-beispiel","color":"yellow"}' \
"$API_BASE/companies/$MILKEE_COMPANY/tags"
# Tag abrufen (ID 1)
curl -H "Authorization: Bearer $MILKEE_TOKEN" \
"$API_BASE/companies/$MILKEE_COMPANY/tags/1"
# Tag aktualisieren (ID 1)
curl -X PUT \
-H "Authorization: Bearer $MILKEE_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"curl-aktualisiert","color":"red"}' \
"$API_BASE/companies/$MILKEE_COMPANY/tags/1"
# Tag löschen (ID 1)
curl -X DELETE \
-H "Authorization: Bearer $MILKEE_TOKEN" \
"$API_BASE/companies/$MILKEE_COMPANY/tags/1"
Erweiterte cURL-Beispiele
bash
# Pagination verwenden
curl -H "Authorization: Bearer $MILKEE_TOKEN" \
"$API_BASE/companies/$MILKEE_COMPANY/tags?page=2&per_page=50"
# Mit detaillierter Response-Information
curl -v \
-H "Authorization: Bearer $MILKEE_TOKEN" \
"$API_BASE/companies/$MILKEE_COMPANY/tags"
# Fehlerbehandlung mit jq
curl -s \
-H "Authorization: Bearer $MILKEE_TOKEN" \
"$API_BASE/companies/$MILKEE_COMPANY/tags" | \
jq '.data[] | {id: .id, name: .name, color: .color}'
# Batch-Erstellung von Tags
for tag in "ausgaben-büro:blue" "ausgaben-reise:turquoise" "einnahmen:green"; do
name=${tag%:*}
color=${tag#*:}
echo "Erstelle Tag: $name ($color)"
curl -s -X POST \
-H "Authorization: Bearer $MILKEE_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"name\":\"$name\",\"color\":\"$color\"}" \
"$API_BASE/companies/$MILKEE_COMPANY/tags" | \
jq '.id, .name'
sleep 1 # Rate Limiting beachten
done