portamer 0.0.1
A comprehensive Python client for Portainer CE API v2.33.3 (generated by Amazon Q)
Requires Python: >=3.8
Keywords: portainer, ce, api, docker, kubernetes, containers, v2.33.3, amazon-q

# Portamer

A comprehensive Python client library for the Portainer API that implements **all available endpoints** from the official Portainer API specification. This client provides a clean, Pythonic interface to manage Docker containers, Kubernetes clusters, and edge computing environments through Portainer.

**API Version**: Generated specifically for Portainer CE API **v2.33.3** using the official Swagger specification from SwaggerHub.
**Generated by**: Amazon Q Developer

## Features

- ✅ **Complete API Coverage** - All Portainer API endpoints implemented
- ✅ **Multiple Authentication Methods** - JWT tokens and API keys supported  
- ✅ **Type Hints** - Full typing support for better IDE experience
- ✅ **Error Handling** - Proper HTTP error handling with detailed messages
- ✅ **Organized Structure** - Methods logically grouped by functionality
- ✅ **Python 3.8+** - Modern Python support

## Installation

```bash
pip install portamer
```

## Quick Start

### Basic Authentication

```python
from portainer_client import PortainerClient

# Method 1: Username/Password (recommended for scripts)
client = PortainerClient("http://localhost:9000", "admin", "password")

# Method 2: API Key (recommended for applications)
client = PortainerClient("http://localhost:9000", api_key="your-api-key")

try:
    # Get all endpoints
    endpoints = client.get_endpoints()
    print(f"Found {len(endpoints)} endpoints")
    
    # Work with first endpoint
    if endpoints:
        endpoint_id = endpoints[0]["Id"]
        
        # Get containers
        containers = client.get_containers(endpoint_id)
        print(f"Found {len(containers)} containers")
        
        # Get system info
        info = client.get_status()
        print(f"Portainer version: {info.get('Version')}")
        
except Exception as e:
    print(f"Error: {e}")
finally:
    # Always logout when using username/password auth
    client.logout()
```

## Common Usage Patterns

### Working with Docker Containers

```python
from portainer_client import PortainerClient

client = PortainerClient("http://localhost:9000", api_key="your-api-key")

# Get endpoint ID (usually the first one for local Docker)
endpoints = client.get_endpoints()
endpoint_id = endpoints[0]["Id"]

# List all containers
containers = client.get_containers(endpoint_id)
for container in containers:
    print(f"Container: {container['Names'][0]} - Status: {container['State']}")

# Get container details
if containers:
    container_id = containers[0]["Id"]
    details = client.get_container_details(endpoint_id, container_id)
    print(f"Container config: {details['Config']}")
```

### Managing Kubernetes Resources

```python
# Get Kubernetes namespaces
namespaces = client.get_namespaces(endpoint_id)
print(f"Namespaces: {[ns['Name'] for ns in namespaces]}")

# List pods in a namespace
pods = client.get_pods(endpoint_id, namespace="default")
for pod in pods:
    print(f"Pod: {pod['metadata']['name']} - Status: {pod['status']['phase']}")

# Get services
services = client.get_kubernetes_services(endpoint_id, namespace="default")
print(f"Services: {[svc['metadata']['name'] for svc in services]}")
```

### Stack Management

```python
# List all stacks
stacks = client.get_stacks()
for stack in stacks:
    print(f"Stack: {stack['Name']} - Type: {stack['Type']}")

# Create a new Docker Compose stack
stack_config = {
    "name": "my-app",
    "stackFileContent": """
version: '3.8'
services:
  web:
    image: nginx:latest
    ports:
      - "80:80"
""",
    "env": []
}
new_stack = client.create_swarm_stack_from_string(
    endpointId=endpoint_id,
    **stack_config
)
```

### Edge Computing

```python
# List edge groups
edge_groups = client.get_edge_groups()
print(f"Edge groups: {[group['Name'] for group in edge_groups]}")

# Create edge job
edge_job = client.create_edge_job(
    name="system-update",
    cronExpression="0 2 * * *",  # Daily at 2 AM
    script="apt update && apt upgrade -y",
    endpoints=[endpoint_id]
)
```

## Error Handling

All methods raise `requests.HTTPError` on API errors. Handle them appropriately:

```python
import requests
from portainer_client import PortainerClient

client = PortainerClient("http://localhost:9000", "admin", "password")

try:
    endpoints = client.get_endpoints()
except requests.HTTPError as e:
    if e.response.status_code == 401:
        print("Authentication failed - check credentials")
    elif e.response.status_code == 403:
        print("Access denied - insufficient permissions")
    elif e.response.status_code == 404:
        print("Resource not found")
    else:
        print(f"API Error: {e.response.status_code} - {e.response.text}")
except requests.ConnectionError:
    print("Cannot connect to Portainer server")
```

## API Coverage

This client implements **ALL** endpoints from the Portainer API specification:

### Authentication & Authorization
- `authenticate(username, password)` - Login with JWT token
- `logout()` - Logout and clear session
- `validate_oauth(code)` - OAuth authentication

### Docker Operations
- **Containers**: List, inspect, start, stop, restart, remove containers
- **Images**: List, pull, remove, inspect Docker images  
- **Networks**: Manage Docker networks
- **Volumes**: Create and manage Docker volumes
- **Services**: Docker Swarm service management

### Kubernetes Management
- **Pods**: List, create, delete, get logs from pods
- **Services**: Manage Kubernetes services and load balancers
- **Deployments**: Create and manage application deployments
- **ConfigMaps & Secrets**: Configuration and secret management
- **Namespaces**: Namespace creation and management
- **Ingress**: Ingress controller and routing management
- **RBAC**: Role-based access control (roles, bindings, service accounts)

### Edge Computing
- **Edge Groups**: Organize and manage edge devices
- **Edge Jobs**: Schedule and execute jobs on edge devices
- **Edge Stacks**: Deploy applications to edge environments

### Stack Management
- **Docker Compose**: Deploy and manage multi-container applications
- **Kubernetes Stacks**: Deploy Kubernetes applications from YAML
- **Git Integration**: Deploy from Git repositories
- **Template Support**: Use predefined application templates

### User & Team Management
- **Users**: Create, update, delete user accounts
- **Teams**: Organize users into teams
- **Roles**: Assign permissions and access levels
- **API Keys**: Generate and manage API authentication keys

### System Administration
- **Settings**: Configure Portainer system settings
- **Registries**: Manage Docker registries and repositories
- **Templates**: Custom and community application templates
- **Backup/Restore**: System backup and disaster recovery
- **Monitoring**: System status and resource monitoring

### Advanced Features
- **WebSocket Support**: Real-time container logs and terminal access
- **LDAP Integration**: Enterprise directory authentication
- **SSL/TLS**: Certificate management and secure connections
- **Resource Controls**: Fine-grained access control
- **Webhooks**: Automated deployment triggers
- **Open AMT**: Intel AMT device management

## Method Examples

### Container Management
```python
# List containers
containers = client.get_containers(endpoint_id)

# Get container details
details = client.get_container_details(endpoint_id, container_id)

# Container operations
client.start_container(endpoint_id, container_id)
client.stop_container(endpoint_id, container_id)
client.restart_container(endpoint_id, container_id)
```

### Kubernetes Operations
```python
# Namespace management
namespaces = client.get_namespaces(endpoint_id)
client.create_namespace(endpoint_id, name="my-namespace")

# Pod operations
pods = client.get_pods(endpoint_id, namespace="default")
client.delete_pod(endpoint_id, namespace="default", name="pod-name")

# Service management
services = client.get_kubernetes_services(endpoint_id, namespace="default")
client.create_kubernetes_service(endpoint_id, namespace="default", **service_config)
```

### Stack Deployment
```python
# Deploy Docker Compose stack
stack = client.create_swarm_stack_from_string(
    endpointId=endpoint_id,
    name="my-app",
    stackFileContent=compose_yaml,
    env=[]
)

# Deploy Kubernetes application
k8s_stack = client.create_kubernetes_stack_from_string(
    endpointId=endpoint_id,
    name="k8s-app", 
    stackFileContent=kubernetes_yaml,
    namespace="default"
)
```

## Requirements

- **Python**: 3.8 or higher
- **Dependencies**: requests >= 2.25.0
- **Portainer**: Compatible with Portainer CE v2.33.3 (generated from official SwaggerHub specification)

## API Specification

This client is generated from the official Portainer CE API v2.33.3 Swagger specification available on SwaggerHub. All endpoints and data structures match the official API documentation for maximum compatibility and reliability.

**Generated by**: Amazon Q Developer using the official Portainer CE v2.33.3 specification.

## License

MIT License - see LICENSE file for details.
```

## API Coverage

This client implements **ALL** endpoints from the Portainer API swagger specification:

### Authentication
- `authenticate(username, password)` - Login and get JWT token
- `logout()` - Logout and clear token
- `validate_oauth(code)` - OAuth authentication

### Backup & Restore
- `create_backup(password=None)` - Create system backup
- `restore_backup(file_content, file_name, password=None)` - Restore from backup

### Custom Templates
- `get_custom_templates(template_types, edge=None)` - List custom templates
- `get_custom_template(template_id)` - Get specific template
- `create_custom_template_from_file(**kwargs)` - Create from file
- `create_custom_template_from_repository(**kwargs)` - Create from repository
- `create_custom_template_from_string(**kwargs)` - Create from string
- `update_custom_template(template_id, **kwargs)` - Update template
- `delete_custom_template(template_id)` - Delete template
- `get_custom_template_file(template_id)` - Get template file
- `git_fetch_custom_template(template_id)` - Git fetch template

### Docker Operations
- `get_container_gpus(environment_id, container_id)` - Get container GPUs
- `get_docker_dashboard(environment_id)` - Get Docker dashboard
- `get_docker_images(environment_id)` - Get Docker images
- `docker_request(endpoint_id, method, path, **kwargs)` - Direct Docker API proxy
- `get_containers(endpoint_id)` - Get containers
- `get_images(endpoint_id)` - Get images

### Endpoints Management
- `get_endpoints()` - List all endpoints
- `create_endpoint(**kwargs)` - Create endpoint
- `get_endpoint(endpoint_id)` - Get specific endpoint
- `update_endpoint(endpoint_id, **kwargs)` - Update endpoint
- `delete_endpoint(endpoint_id)` - Delete endpoint
- `delete_endpoints_batch(endpoints)` - Delete multiple endpoints
- `update_endpoint_association(endpoint_id, **kwargs)` - Update association
- `get_endpoint_dockerhub_status(endpoint_id, registry_id)` - DockerHub status
- `force_update_service(endpoint_id, **kwargs)` - Force service update
- `get_endpoint_registries(endpoint_id)` - Get endpoint registries
- `update_endpoint_registry_access(endpoint_id, registry_id, **kwargs)` - Update registry access
- `update_endpoint_settings(endpoint_id, **kwargs)` - Update settings
- `snapshot_endpoint(endpoint_id)` - Snapshot endpoint
- `create_global_key()` - Create global key
- `update_endpoint_relations(**kwargs)` - Update relations
- `snapshot_endpoints()` - Snapshot all endpoints

### Edge Computing
- `get_edge_groups()` - List edge groups
- `create_edge_group(**kwargs)` - Create edge group
- `get_edge_group(group_id)` - Get edge group
- `update_edge_group(group_id, **kwargs)` - Update edge group
- `delete_edge_group(group_id)` - Delete edge group
- `get_edge_jobs()` - List edge jobs
- `create_edge_job(**kwargs)` - Create edge job
- `get_edge_job(job_id)` - Get edge job
- `update_edge_job(job_id, **kwargs)` - Update edge job
- `delete_edge_job(job_id)` - Delete edge job
- `get_edge_job_file(job_id)` - Get job file
- `get_edge_job_tasks(job_id)` - Get job tasks
- `get_edge_job_task_logs(job_id, task_id)` - Get task logs
- `clear_edge_job_task_logs(job_id, task_id)` - Clear task logs
- `create_edge_job_from_file(**kwargs)` - Create job from file
- `create_edge_job_from_string(**kwargs)` - Create job from string
- `get_edge_stacks()` - List edge stacks
- `create_edge_stack(**kwargs)` - Create edge stack
- `get_edge_stack(stack_id)` - Get edge stack
- `update_edge_stack(stack_id, **kwargs)` - Update edge stack
- `delete_edge_stack(stack_id)` - Delete edge stack
- `get_edge_stack_file(stack_id)` - Get stack file
- `update_edge_stack_status(stack_id, **kwargs)` - Update stack status
- `create_edge_stack_from_file(**kwargs)` - Create from file
- `create_edge_stack_from_repository(**kwargs)` - Create from repository
- `create_edge_stack_from_string(**kwargs)` - Create from string
- `collect_edge_job_logs(endpoint_id, job_id, **kwargs)` - Collect job logs
- `get_edge_stack_status(endpoint_id, stack_id)` - Get stack status
- `get_endpoint_edge_status(endpoint_id)` - Get edge status

### Kubernetes Management
- `get_helm_charts(endpoint_id, **params)` - List Helm charts
- `install_helm_chart(endpoint_id, **kwargs)` - Install Helm chart
- `get_helm_release(endpoint_id, name, **params)` - Get Helm release
- `uninstall_helm_release(endpoint_id, release, **params)` - Uninstall release
- `get_helm_release_history(endpoint_id, release, **params)` - Get release history
- `rollback_helm_release(endpoint_id, release, **kwargs)` - Rollback release
- `get_kubernetes_applications(endpoint_id, **params)` - List applications
- `create_kubernetes_application(endpoint_id, **kwargs)` - Create application
- `get_kubernetes_applications_count(endpoint_id)` - Get applications count
- `get_cluster_role_bindings(endpoint_id)` - List cluster role bindings
- `create_cluster_role_binding(endpoint_id, **kwargs)` - Create cluster role binding
- `delete_cluster_role_bindings(endpoint_id, **kwargs)` - Delete cluster role bindings
- `get_cluster_roles(endpoint_id)` - List cluster roles
- `create_cluster_role(endpoint_id, **kwargs)` - Create cluster role
- `delete_cluster_roles(endpoint_id, **kwargs)` - Delete cluster roles
- `get_configmaps(endpoint_id, **params)` - List ConfigMaps
- `create_configmap(endpoint_id, **kwargs)` - Create ConfigMap
- `get_configmaps_count(endpoint_id)` - Get ConfigMaps count
- `get_cron_jobs(endpoint_id, **params)` - List Cron Jobs
- `create_cron_job(endpoint_id, **kwargs)` - Create Cron Job
- `delete_cron_jobs(endpoint_id, **kwargs)` - Delete Cron Jobs
- `get_kubernetes_dashboard(endpoint_id)` - Get dashboard
- `describe_kubernetes_resource(endpoint_id, **params)` - Describe resource
- `get_kubernetes_events(endpoint_id, **params)` - List events
- `get_ingress_controllers(endpoint_id)` - List ingress controllers
- `update_ingress_controllers(endpoint_id, **kwargs)` - Update ingress controllers
- `get_ingresses(endpoint_id, **params)` - List ingresses
- `create_ingress(endpoint_id, **kwargs)` - Create ingress
- `get_ingresses_count(endpoint_id)` - Get ingresses count
- `delete_ingresses(endpoint_id, **kwargs)` - Delete ingresses
- `get_kubernetes_jobs(endpoint_id, **params)` - List Jobs
- `create_kubernetes_job(endpoint_id, **kwargs)` - Create Job
- `delete_kubernetes_jobs(endpoint_id, **kwargs)` - Delete Jobs
- `get_max_resource_limits(endpoint_id)` - Get max resource limits
- `get_nodes_limits(endpoint_id)` - Get nodes limits
- `get_applications_resources_metrics(endpoint_id, **params)` - Get app metrics
- `get_nodes_metrics(endpoint_id)` - Get nodes metrics
- `get_node_metrics(endpoint_id, name)` - Get node metrics
- `get_pods_metrics(endpoint_id, namespace)` - Get pods metrics
- `get_pod_metrics(endpoint_id, namespace, name)` - Get pod metrics

### Namespaces
- `get_namespaces(endpoint_id, **params)` - List namespaces
- `create_namespace(endpoint_id, **kwargs)` - Create namespace
- `get_namespace(endpoint_id, namespace)` - Get namespace
- `update_namespace(endpoint_id, namespace, **kwargs)` - Update namespace
- `delete_namespace(endpoint_id, namespace)` - Delete namespace
- `get_namespace_configmap(endpoint_id, namespace, configmap)` - Get ConfigMap
- `get_namespace_events(endpoint_id, namespace)` - Get events
- `get_namespace_ingress_controllers(endpoint_id, namespace)` - Get ingress controllers
- `update_namespace_ingress_controllers(endpoint_id, namespace, **kwargs)` - Update controllers
- `get_namespace_ingresses(endpoint_id, namespace, **params)` - Get ingresses
- `create_namespace_ingress(endpoint_id, namespace, **kwargs)` - Create ingress
- `get_namespace_ingress(endpoint_id, namespace, ingress)` - Get ingress
- `update_namespace_ingress(endpoint_id, namespace, ingress, **kwargs)` - Update ingress
- `get_namespace_secret(endpoint_id, namespace, secret)` - Get secret
- `get_namespace_services(endpoint_id, namespace, **params)` - Get services
- `create_namespace_service(endpoint_id, namespace, **kwargs)` - Create service
- `update_namespace_system(endpoint_id, namespace, **kwargs)` - Update system
- `get_namespace_volumes(endpoint_id, namespace, **params)` - Get volumes
- `get_namespaces_count(endpoint_id)` - Get namespaces count

### Stacks Management
- `get_stacks(**params)` - List stacks
- `create_stack(**kwargs)` - Create stack
- `get_stack(stack_id)` - Get stack
- `update_stack(stack_id, **kwargs)` - Update stack
- `delete_stack(stack_id, **params)` - Delete stack
- `associate_stack(stack_id, **kwargs)` - Associate stack
- `get_stack_file(stack_id)` - Get stack file
- `git_redeploy_stack(stack_id, **kwargs)` - Git redeploy
- `redeploy_stack_git(stack_id, **kwargs)` - Redeploy from git
- `migrate_stack(stack_id, **kwargs)` - Migrate stack
- `start_stack(stack_id)` - Start stack
- `stop_stack(stack_id)` - Stop stack
- `create_kubernetes_stack_from_repository(**kwargs)` - Create K8s from repo
- `create_kubernetes_stack_from_string(**kwargs)` - Create K8s from string
- `create_kubernetes_stack_from_url(**kwargs)` - Create K8s from URL
- `create_standalone_stack_from_file(**kwargs)` - Create standalone from file
- `create_standalone_stack_from_repository(**kwargs)` - Create standalone from repo
- `create_standalone_stack_from_string(**kwargs)` - Create standalone from string
- `create_swarm_stack_from_file(**kwargs)` - Create swarm from file
- `create_swarm_stack_from_repository(**kwargs)` - Create swarm from repo
- `create_swarm_stack_from_string(**kwargs)` - Create swarm from string
- `delete_stack_by_name(name, **params)` - Delete by name
- `execute_stack_webhook(webhook_id)` - Execute webhook

### Users Management
- `get_users()` - List users
- `create_user(**kwargs)` - Create user
- `get_user(user_id)` - Get user
- `update_user(user_id, **kwargs)` - Update user
- `delete_user(user_id)` - Delete user
- `get_user_helm_repositories(user_id)` - Get Helm repositories
- `create_user_helm_repository(user_id, **kwargs)` - Create Helm repository
- `delete_user_helm_repository(user_id, repository_id)` - Delete Helm repository
- `get_user_memberships(user_id)` - Get memberships
- `update_user_password(user_id, **kwargs)` - Update password
- `get_user_tokens(user_id)` - Get tokens
- `create_user_token(user_id, **kwargs)` - Create token
- `delete_user_token(user_id, key_id)` - Delete token
- `check_admin_user()` - Check admin user
- `init_admin_user(**kwargs)` - Initialize admin user
- `get_current_user()` - Get current user

### System Management
- `get_status()` - Get status
- `get_system_info()` - Get system info
- `get_system_nodes()` - Get system nodes
- `get_system_status()` - Get system status
- `upgrade_system(**kwargs)` - Upgrade system
- `get_system_version()` - Get system version

### Settings
- `get_settings()` - Get settings
- `update_settings(**kwargs)` - Update settings
- `get_public_settings()` - Get public settings

### Registries
- `get_registries()` - List registries
- `create_registry(**kwargs)` - Create registry
- `get_registry(registry_id)` - Get registry
- `update_registry(registry_id, **kwargs)` - Update registry
- `delete_registry(registry_id)` - Delete registry
- `configure_registry(registry_id, **kwargs)` - Configure registry

### Additional Features
- Teams and team memberships management
- Tags management
- Roles and RBAC
- Resource controls
- Webhooks
- Templates (App and Helm)
- SSL/TLS certificate management
- LDAP integration
- Open AMT device management
- WebSocket endpoints for real-time operations
- GitOps integration
- Backup and restore functionality

## Error Handling

All methods raise `requests.HTTPError` on API errors. Handle them appropriately:

```python
try:
    endpoints = client.get_endpoints()
except requests.HTTPError as e:
    print(f"API Error: {e.response.status_code} - {e.response.text}")
```

## WebSocket Support

For WebSocket operations, the client provides URL generators:

```python
# Get WebSocket URLs for real-time operations
attach_url = client.get_websocket_attach_url()
exec_url = client.get_websocket_exec_url()
k8s_shell_url = client.get_websocket_kubernetes_shell_url()
pod_url = client.get_websocket_pod_url()
```

## Architecture

The client is organized into mixins for better maintainability:
- `PortainerDockerMixin` - Docker and endpoint operations
- `PortainerEdgeMixin` - Edge computing features
- `PortainerKubernetesMixin` - Kubernetes operations
- `PortainerRemainingMixin` - All other API endpoints

## License

This library implements the Portainer API as documented in their swagger.yaml specification.