Integração com API

Guia completo para integrar seus sistemas com a API do DeployAlly.

Visão Geral

A API REST permite automatizar deployments, integrar com CI/CD e criar ferramentas customizadas.

Ambientes

Ambiente Base URL Uso
Produção https://sys.deployally.com/api/v1 Sistemas em produção
Teste https://dev.sys.deployally.com/api/v1 Desenvolvimento e testes

Configuração Inicial

1. Obter API Key

Acesse o Dashboard e crie uma API Key:

  1. Login em https://app.deployally.com
  2. Configurações > API Keys > Criar Nova
  3. Defina permissões necessárias
  4. Copie e armazene a key com segurança

2. Configurar Ambiente

# Variáveis de ambiente
export DEPLOYALLY_API_URL="https://sys.deployally.com/api/v1"
export DEPLOYALLY_API_KEY="da_xxx"

3. Testar Conexão

curl -X GET "${DEPLOYALLY_API_URL}/health"
curl -X GET "${DEPLOYALLY_API_URL}/templates" \
  -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}"

Ambiente de Teste

Para desenvolvimento, use o ambiente de teste com dados isolados.

Configuração de Teste

export DEPLOYALLY_API_URL="https://dev.sys.deployally.com/api/v1"
export DEPLOYALLY_API_KEY="da_test_xxx"  # Key do ambiente de teste

Características do Ambiente de Teste

  • Dados resetados semanalmente
  • Rate limits mais baixos
  • Templates de teste disponíveis
  • Sem cobrança

Criando Dados de Teste

# Registrar servidor de teste
curl -X POST "${DEPLOYALLY_API_URL}/servers" \
  -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "test-server-01",
    "environment": "development"
  }'

# Criar definition de teste
curl -X POST "${DEPLOYALLY_API_URL}/definitions" \
  -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "template_id": "tpl_mysql_84",
    "server_id": "srv_test123",
    "name": "mysql_teste",
    "params": {
      "root_password": "test_password",
      "database_name": "test_db",
      "user_name": "test_user",
      "user_password": "test_user_pass"
    },
    "profile": "minimal"
  }'

Fluxo de Integração

Deploy Automatizado

1. Listar templates    → GET /templates
2. Criar definition    → POST /definitions
3. Executar deploy     → POST /deployments
4. Verificar status    → GET /deployments/{id}
5. Monitorar instance  → GET /instances

Exemplo Completo

# 1. Buscar template MySQL
TEMPLATE=$(curl -s "${DEPLOYALLY_API_URL}/templates?species=mysql&version=8.4" \
  -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" | jq -r '.data[0].id')

# 2. Criar definition
DEFINITION=$(curl -s -X POST "${DEPLOYALLY_API_URL}/definitions" \
  -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{
    \"template_id\": \"${TEMPLATE}\",
    \"server_id\": \"srv_123\",
    \"name\": \"mysql_app_principal\",
    \"params\": {
      \"root_password\": \"$(openssl rand -base64 24)\",
      \"database_name\": \"app_db\",
      \"user_name\": \"app_user\",
      \"user_password\": \"$(openssl rand -base64 16)\"
    },
    \"profile\": \"production\"
  }" | jq -r '.data.id')

# 3. Executar deploy
DEPLOY=$(curl -s -X POST "${DEPLOYALLY_API_URL}/deployments" \
  -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{\"definition_id\": \"${DEFINITION}\"}" | jq -r '.data.id')

# 4. Aguardar conclusão
while true; do
  STATUS=$(curl -s "${DEPLOYALLY_API_URL}/deployments/${DEPLOY}" \
    -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" | jq -r '.data.status')

  if [ "$STATUS" = "success" ]; then
    echo "Deploy concluído!"
    break
  elif [ "$STATUS" = "failed" ]; then
    echo "Deploy falhou!"
    exit 1
  fi

  sleep 5
done

Integração com CI/CD

GitHub Actions

name: Deploy to DeployAlly

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Trigger Deployment
        env:
          DEPLOYALLY_API_KEY: ${{ secrets.DEPLOYALLY_API_KEY }}
        run: |
          curl -X POST "https://sys.deployally.com/api/v1/deployments" \
            -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" \
            -H "Content-Type: application/json" \
            -d '{"definition_id": "def_app_principal"}'

GitLab CI

deploy:
  stage: deploy
  script:
    - |
      curl -X POST "https://sys.deployally.com/api/v1/deployments" \
        -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" \
        -H "Content-Type: application/json" \
        -d '{"definition_id": "def_app_principal"}'
  only:
    - main

Webhooks

Configure webhooks para receber notificações de eventos.

Configurar Webhook

curl -X POST "${DEPLOYALLY_API_URL}/webhooks" \
  -H "Authorization: Bearer ${DEPLOYALLY_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://meu-sistema.com/webhook/deployally",
    "events": [
      "deployment.success",
      "deployment.failed",
      "instance.unhealthy"
    ],
    "secret": "meu_webhook_secret"
  }'

Receber Webhook

from flask import Flask, request
import hmac
import hashlib

app = Flask(__name__)
WEBHOOK_SECRET = "meu_webhook_secret"

@app.route('/webhook/deployally', methods=['POST'])
def handle_webhook():
    # Verificar assinatura
    signature = request.headers.get('X-DeployAlly-Signature')
    payload = request.get_data()
    expected = hmac.new(
        WEBHOOK_SECRET.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()

    if not hmac.compare_digest(signature, expected):
        return 'Invalid signature', 403

    # Processar evento
    event = request.json
    event_type = event['type']

    if event_type == 'deployment.success':
        # Notificar equipe, atualizar status, etc
        pass
    elif event_type == 'instance.unhealthy':
        # Alertar, tentar restart, etc
        pass

    return 'OK', 200

Tratamento de Erros

Retry com Backoff

import requests
import time

def api_request(method, endpoint, **kwargs):
    url = f"{DEPLOYALLY_API_URL}{endpoint}"
    headers = {
        "Authorization": f"Bearer {DEPLOYALLY_API_KEY}",
        "Content-Type": "application/json"
    }

    max_retries = 3
    for attempt in range(max_retries):
        try:
            response = requests.request(
                method, url, headers=headers, **kwargs
            )

            if response.status_code == 429:
                # Rate limited - aguardar e tentar novamente
                retry_after = int(response.headers.get('Retry-After', 60))
                time.sleep(retry_after)
                continue

            response.raise_for_status()
            return response.json()

        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # Exponential backoff

    raise Exception("Max retries exceeded")

Códigos de Erro Comuns

Código Causa Ação
401 Key inválida Verificar API Key
403 Sem permissão Verificar permissões da key
404 Recurso não existe Verificar IDs
422 Dados inválidos Verificar payload
429 Rate limit Aguardar e retry
500 Erro interno Retry com backoff

Boas Práticas

Segurança

  1. Nunca exponha API Keys em logs ou código
  2. Use variáveis de ambiente ou secrets managers
  3. Rotacione keys periodicamente
  4. Use permissões mínimas necessárias
  5. Configure IP allowlist quando possível

Performance

  1. Use paginação para listagens grandes
  2. Implemente cache para dados estáticos (templates)
  3. Use webhooks ao invés de polling
  4. Agrupe operações quando possível

Resiliência

  1. Implemente retry com backoff exponencial
  2. Trate rate limits adequadamente
  3. Valide respostas antes de usar
  4. Tenha fallbacks para falhas

Próximos Passos

By Borlot.com.br on 13/02/2026