Skip to main content

Overview

Orphelix provides a RESTful API for managing Kubernetes resources and accessing cluster data. All API endpoints are server-side Next.js API routes that communicate with the Kubernetes API.

Resources

Deployments, Pods, Nodes, Services, ConfigMaps, Secrets

Real-time

Server-Sent Events for live updates

GitHub

Repository browsing and PR creation

AI Features

File matching and troubleshooting

Base URL

http://localhost:3000/api
Production:
https://your-domain.com/api

Authentication

GitHub OAuth

Most endpoints work without authentication. GitHub integration requires OAuth:
# Login endpoint
GET /api/auth/signin
Session cookie:
  • next-auth.session-token (httpOnly, secure)

Kubernetes Access

API uses kubeconfig from server’s filesystem:
  • ~/.kube/config
  • Or $KUBECONFIG environment variable

Request Format

Query Parameters

All resource endpoints accept:
interface QueryParams {
  namespace?: string    // Kubernetes namespace (required for most endpoints)
  context?: string      // Kubeconfig context (optional, uses current context if not provided)
}
Example:
GET /api/deployments?namespace=default&context=minikube

Headers

Content-Type: application/json
Accept: application/json

Response Format

Success Response

{
  "data": [...],
  "metadata": {
    "count": 10,
    "namespace": "default",
    "timestamp": "2025-01-28T10:00:00Z"
  }
}

Error Response

{
  "error": "Resource not found",
  "code": "NOT_FOUND",
  "details": {
    "resource": "deployment",
    "name": "nginx",
    "namespace": "default"
  }
}

HTTP Status Codes

CodeMeaning
200Success
201Created
400Bad Request
401Unauthorized
403Forbidden (RBAC)
404Not Found
500Internal Server Error
503Service Unavailable

Rate Limiting

No rate limiting currently implemented. For production deployments, consider:
  • nginx rate limiting
  • API gateway
  • Custom middleware

Pagination

Not currently implemented. All list endpoints return full results. For large clusters:
  • Use namespace filtering
  • Implement label selectors
  • Future: Add limit and offset params

Error Handling

Kubernetes API Errors

{
  "error": "Forbidden: User cannot get resource \"deployments\" in API group \"apps\" in namespace \"production\"",
  "code": "FORBIDDEN",
  "statusCode": 403
}

Connection Errors

{
  "error": "Unable to connect to cluster",
  "code": "CONNECTION_ERROR",
  "details": {
    "message": "ECONNREFUSED"
  }
}

Demo Mode

When app is in demo mode, API returns mock data:
# Check mode
GET /api/settings

# Response
{
  "mode": "demo",  // or "real"
  "selectedContext": null,
  "selectedNamespace": "default"
}
Demo mode features:
  • No kubeconfig required
  • Realistic mock data
  • All endpoints functional
  • Perfect for testing

API Endpoints Overview

Resources

EndpointMethodDescription
/api/deploymentsGETList deployments
/api/deployments/[name]GETGet deployment details
/api/deployments/[name]/restartPOSTRestart deployment
/api/deployments/[name]/podsGETGet deployment pods
/api/deployments/[name]/eventsGETGet deployment events
/api/podsGETList pods
/api/pods/[name]GETGet pod details
/api/pods/[name]/logsGETStream pod logs
/api/pods/[name]/restartPOSTDelete pod (restart)
/api/pods/[name]/eventsGETGet pod events
/api/nodesGETList nodes
/api/nodes/[name]GETGet node details
/api/nodes/[name]/podsGETGet node pods
/api/nodes/[name]/eventsGETGet node events
/api/servicesGETList services
/api/services/[name]GETGet service details
/api/configmapsGETList ConfigMaps
/api/configmaps/[name]GETGet ConfigMap details
/api/secretsGETList Secrets
/api/secrets/[name]GETGet Secret details
/api/eventsGETList all events
/api/hpaGETList HPAs
/api/statefulsetsGETList StatefulSets
/api/daemonsetsGETList DaemonSets
/api/jobsGETList Jobs
/api/cronjobsGETList CronJobs
/api/ingressGETList Ingress
/api/namespacesGETList namespaces
/api/namespaces/[name]GETGet namespace details

Dashboard

EndpointMethodDescription
/api/dashboard/summaryGETCluster summary stats
/api/cluster-healthGETCluster health score

Real-time

EndpointMethodDescription
/api/streamGETSSE for live updates

GitHub

EndpointMethodDescription
/api/github/reposGETList repositories
/api/github/treeGETBrowse repository files
/api/github/fileGETGet file content
/api/github/branchesGETList branches
/api/github/create-prPOSTCreate pull request
/api/github/create-multi-file-prPOSTCreate multi-file PR
/api/github/match-filePOSTAI file matching

AI

EndpointMethodDescription
/api/ai/match-filePOSTMatch deployment to file
/api/ai/troubleshootPOSTTroubleshoot issues

Settings

EndpointMethodDescription
/api/settingsGETGet user settings
/api/settingsPOSTUpdate settings
/api/settingsDELETEReset settings
/api/contextsGETList kubeconfig contexts
/api/test-connectionGETTest cluster connection

Common Patterns

Listing Resources

// Request
GET /api/deployments?namespace=default

// Response
{
  "deployments": [
    {
      "name": "nginx",
      "namespace": "default",
      "replicas": {
        "desired": 3,
        "ready": 3,
        "available": 3
      },
      "status": "Available",
      "age": "5d",
      "images": ["nginx:1.21"]
    }
  ]
}

Getting Resource Details

// Request
GET /api/deployments/nginx?namespace=default

// Response
{
  "name": "nginx",
  "namespace": "default",
  "replicas": {
    "desired": 3,
    "ready": 3,
    "available": 3,
    "unavailable": 0
  },
  "status": "Available",
  "conditions": [
    {
      "type": "Available",
      "status": "True",
      "reason": "MinimumReplicasAvailable"
    }
  ],
  "strategy": {
    "type": "RollingUpdate",
    "rollingUpdate": {
      "maxSurge": 1,
      "maxUnavailable": 0
    }
  },
  "selector": {
    "app": "nginx"
  },
  "template": {
    "metadata": {
      "labels": {
        "app": "nginx"
      }
    },
    "spec": {
      "containers": [
        {
          "name": "nginx",
          "image": "nginx:1.21",
          "ports": [
            {
              "containerPort": 80,
              "protocol": "TCP"
            }
          ]
        }
      ]
    }
  },
  "createdAt": "2025-01-23T10:00:00Z"
}

Updating Resources

// Request
POST /api/deployments/nginx/restart?namespace=default

// Response
{
  "success": true,
  "message": "Deployment restarted",
  "timestamp": "2025-01-28T10:00:00Z"
}

SDK / Client Libraries

Official SDK: Coming soon Manual Implementation:
// TypeScript example
class OrphelixAPI {
  constructor(private baseURL: string) {}

  async getDeployments(namespace: string, context?: string) {
    const params = new URLSearchParams({ namespace })
    if (context) params.append('context', context)
    
    const res = await fetch(`${this.baseURL}/deployments?${params}`)
    if (!res.ok) throw new Error(await res.text())
    
    return res.json()
  }

  async restartDeployment(name: string, namespace: string) {
    const res = await fetch(
      `${this.baseURL}/deployments/${name}/restart`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ namespace }),
      }
    )
    
    if (!res.ok) throw new Error(await res.text())
    return res.json()
  }
}

// Usage
const api = new OrphelixAPI('http://localhost:3000/api')
const deployments = await api.getDeployments('default')

WebSocket Alternative

Orphelix uses Server-Sent Events (SSE) instead of WebSocket for real-time updates. Why SSE:
  • Simpler protocol (HTTP)
  • Automatic reconnection
  • One-way communication (sufficient for monitoring)
  • Built into browsers
See Real-time API for details.

API Versioning

Current version: v1 (implicit) No versioning prefix currently used. Future versions may use:
/api/v2/deployments
Breaking changes will be announced in release notes.

OpenAPI Specification

Coming soon: OpenAPI 3.0 spec for automatic client generation Will be available at:
GET /api/openapi.json

Examples

cURL

# List deployments
curl http://localhost:3000/api/deployments?namespace=default

# Get deployment
curl http://localhost:3000/api/deployments/nginx?namespace=default

# Restart deployment
curl -X POST http://localhost:3000/api/deployments/nginx/restart \
  -H "Content-Type: application/json" \
  -d '{"namespace":"default"}'

# Stream logs
curl http://localhost:3000/api/pods/nginx-abc123/logs?namespace=default&follow=true

# SSE stream
curl -N http://localhost:3000/api/stream?namespace=default

JavaScript (fetch)

// List deployments
const deployments = await fetch('/api/deployments?namespace=default')
  .then(res => res.json())

// Restart deployment
const result = await fetch('/api/deployments/nginx/restart', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ namespace: 'default' })
}).then(res => res.json())

// SSE stream
const eventSource = new EventSource('/api/stream?namespace=default')
eventSource.addEventListener('deployment', (e) => {
  const data = JSON.parse(e.data)
  console.log('Deployment updated:', data)
})

Python

import requests

# List deployments
response = requests.get(
    'http://localhost:3000/api/deployments',
    params={'namespace': 'default'}
)
deployments = response.json()

# Restart deployment
response = requests.post(
    'http://localhost:3000/api/deployments/nginx/restart',
    json={'namespace': 'default'}
)
result = response.json()

# SSE stream
import sseclient

response = requests.get(
    'http://localhost:3000/api/stream',
    params={'namespace': 'default'},
    stream=True
)

client = sseclient.SSEClient(response)
for event in client.events():
    if event.event == 'deployment':
        print(f'Deployment updated: {event.data}')

Rate Limits & Best Practices

Recommendations

  1. Use SSE for real-time updates - Don’t poll
  2. Cache responses - Use staleTime in React Query
  3. Batch requests - Fetch related data together
  4. Use namespaces - Filter by namespace when possible
  5. Handle errors gracefully - Retry with exponential backoff

Example with React Query

import { useQuery } from '@tanstack/react-query'

function useDeployments(namespace: string) {
  return useQuery({
    queryKey: ['deployments', namespace],
    queryFn: async () => {
      const res = await fetch(`/api/deployments?namespace=${namespace}`)
      if (!res.ok) throw new Error('Failed to fetch')
      return res.json()
    },
    staleTime: 10_000,      // Cache for 10s
    refetchInterval: 30_000, // Auto-refetch every 30s
    retry: 3,                // Retry 3 times on failure
  })
}

Security

CORS

CORS is disabled by default (same-origin only). To enable for external clients:
// middleware.ts
export function middleware(request: NextRequest) {
  const response = NextResponse.next()
  
  response.headers.set('Access-Control-Allow-Origin', 'https://trusted-domain.com')
  response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
  response.headers.set('Access-Control-Allow-Headers', 'Content-Type')
  
  return response
}

API Keys

Not currently implemented. For API key authentication in future:
Authorization: Bearer your-api-key

Next Steps