DEV Community

Alex Spinov
Alex Spinov

Posted on

ArgoCD Has a Free API: Here's How to Use It for GitOps Automation

ArgoCD is the most popular GitOps tool for Kubernetes, and its REST API lets you manage applications, sync deployments, and monitor cluster state — all programmatically.

Why Use the ArgoCD API?

  • Automate application deployments from CI/CD pipelines
  • Monitor sync status across all environments
  • Build custom deployment dashboards
  • Implement progressive delivery (canary, blue-green)

Getting Started

export ARGOCD_SERVER="localhost:8080"
export ARGOCD_TOKEN="your-auth-token"

# Get auth token
ARGOCD_TOKEN=$(curl -s "https://$ARGOCD_SERVER/api/v1/session" \
  -d '{"username":"admin","password":"your-password"}' | jq -r '.token')

# List all applications
curl -s -H "Authorization: Bearer $ARGOCD_TOKEN" \
  "https://$ARGOCD_SERVER/api/v1/applications" | jq '.items[] | {name: .metadata.name, status: .status.sync.status, health: .status.health.status}'
Enter fullscreen mode Exit fullscreen mode

Python Client

import requests

class ArgoCDClient:
    def __init__(self, server, token=None, username=None, password=None):
        self.url = f"https://{server}/api/v1"
        self.session = requests.Session()
        self.session.verify = False  # For self-signed certs

        if token:
            self.session.headers['Authorization'] = f'Bearer {token}'
        elif username and password:
            resp = self.session.post(f"{self.url}/session", json={'username': username, 'password': password})
            token = resp.json()['token']
            self.session.headers['Authorization'] = f'Bearer {token}'

    def list_apps(self):
        resp = self.session.get(f"{self.url}/applications")
        return resp.json().get('items', [])

    def get_app(self, name):
        resp = self.session.get(f"{self.url}/applications/{name}")
        return resp.json()

    def sync_app(self, name, revision=None, prune=False):
        payload = {'prune': prune}
        if revision:
            payload['revision'] = revision
        resp = self.session.post(f"{self.url}/applications/{name}/sync", json=payload)
        return resp.json()

    def get_app_resources(self, name):
        resp = self.session.get(f"{self.url}/applications/{name}/resource-tree")
        return resp.json()

    def create_app(self, name, repo_url, path, dest_server='https://kubernetes.default.svc', dest_namespace='default', project='default'):
        app = {
            'metadata': {'name': name},
            'spec': {
                'project': project,
                'source': {'repoURL': repo_url, 'path': path, 'targetRevision': 'HEAD'},
                'destination': {'server': dest_server, 'namespace': dest_namespace},
                'syncPolicy': {'automated': {'prune': True, 'selfHeal': True}}
            }
        }
        resp = self.session.post(f"{self.url}/applications", json=app)
        return resp.json()

# Usage
argo = ArgoCDClient('argocd.example.com', username='admin', password='your-password')

# Check all apps
for app in argo.list_apps():
    name = app['metadata']['name']
    sync = app['status']['sync']['status']
    health = app['status']['health']['status']
    print(f"{name:30s} Sync: {sync:12s} Health: {health}")
Enter fullscreen mode Exit fullscreen mode

Deployment Dashboard

def deployment_status(argo):
    apps = argo.list_apps()

    synced = sum(1 for a in apps if a['status']['sync']['status'] == 'Synced')
    healthy = sum(1 for a in apps if a['status']['health']['status'] == 'Healthy')

    print(f"Total: {len(apps)} | Synced: {synced} | Healthy: {healthy}")
    print()

    # Show out-of-sync or unhealthy apps
    problems = [a for a in apps if a['status']['sync']['status'] != 'Synced' or a['status']['health']['status'] != 'Healthy']

    if problems:
        print("ATTENTION NEEDED:")
        for app in problems:
            name = app['metadata']['name']
            sync = app['status']['sync']['status']
            health = app['status']['health']['status']
            print(f"  {name}: sync={sync}, health={health}")
    else:
        print("All applications healthy and synced!")

deployment_status(argo)
Enter fullscreen mode Exit fullscreen mode

Progressive Delivery

import time

def canary_deploy(argo, app_name, new_revision, canary_weight=10, wait_minutes=5):
    print(f"Step 1: Deploy canary ({canary_weight}% traffic)...")
    argo.sync_app(f"{app_name}-canary", revision=new_revision)

    print(f"Step 2: Waiting {wait_minutes} minutes for metrics...")
    time.sleep(wait_minutes * 60)

    # Check canary health
    canary = argo.get_app(f"{app_name}-canary")
    if canary['status']['health']['status'] != 'Healthy':
        print("Canary UNHEALTHY! Rolling back...")
        argo.sync_app(f"{app_name}-canary")  # Sync back to previous
        return False

    print("Step 3: Canary healthy. Promoting to production...")
    argo.sync_app(app_name, revision=new_revision)

    # Wait for production sync
    for i in range(30):
        app = argo.get_app(app_name)
        if app['status']['sync']['status'] == 'Synced' and app['status']['health']['status'] == 'Healthy':
            print(f"Production deployment successful!")
            return True
        time.sleep(10)

    print("Production deployment timed out")
    return False

canary_deploy(argo, 'my-service', 'v2.1.0')
Enter fullscreen mode Exit fullscreen mode

Real-World Use Case

A fintech company managed 150+ microservices on Kubernetes with ArgoCD. They built a deployment portal using the ArgoCD API — product managers could see which version was deployed where, developers could promote staging to production with one click, and the system automatically rolled back if health checks failed within 5 minutes. Deployment incidents dropped 90%.

What You Can Build

  • Deployment dashboard showing all app status in real-time
  • Progressive delivery system with canary and blue-green
  • Auto-rollback based on Prometheus metrics
  • Multi-cluster manager deploying across regions
  • Compliance reporter tracking what's deployed where

Need custom GitOps automation? I build Kubernetes tools and CI/CD pipelines.

Email me: spinov001@gmail.com
Check out my developer tools: https://apify.com/spinov001

Top comments (0)