API optimada da Flux Krea

Implementaziun da Flux optimada cun divers nivels da qualitad.

✓ Divers nivels

✓ Generaziun sperta

✓ Optimà

✓ Pretschs variabels

Autentificaziun

Per acceder a Flux Krea via l'API da Doitong, dovra tia clav d'API da Doitong. Includa quella en la mutaziun GraphQL u en ils headers da l'API REST.

Impurtant: Tegn tia clav d'API da Doitong segira e n'expona quella mai en il code dal client. Fa calls d'API adina nà da tes server backend.
// GraphQL Header
{
  "Authorization": "Bearer YOUR_API_KEY"
}

// REST Header
"X-API-Key": "YOUR_API_KEY"

Start d'immediat

Cumenza cun Flux Krea API en be paucas minutas. Suonda quests simpels pass per generar tes emprim text to image.

Pass 1: Obtegn tia clav d'API

Registrescha in conto da Doitong e navighescha a tes dashboard per generar ina clav d'API.

Pass 2: Fa tia emprima dumonda

Dovra in dals exempels da code sutvart per far tes emprim call d'API.

curl -X POST https://api.doitong.com/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "query": "mutation Generate($input: GenerateInput!) { generate(input: $input) { id status type provider url metadata creditCost } }",
    "variables": {
      "input": {
        "type": "IMAGE",
        "provider": "flux-krea",
        "input": {
          "text": "A futuristic city with flying cars and neon lights"
        },
        "options": {
          "width": 1024,
          "height": 1024
        }
      }
    }
  }'
const response = await fetch('https://api.doitong.com/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  body: JSON.stringify({
    query: `
      mutation GenerateImage($input: ImageGenerationInput!) {
        generateImage(input: $input) {
          id
          url
          width
          height
        }
      }
    `,
    variables: {
      input: {
        service: 'flux-krea',
        prompt: 'A futuristic city with flying cars and neon lights',
        width: 1024,
        height: 1024
      }
    }
  })
});

const data = await response.json();
console.log('Image:', data.data.generateImage);
import requests
import json

url = "https://api.doitong.com/graphql"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"
}

query = """
mutation Generate($input: GenerateInput!) {
  generate(input: $input) {
    id
    status
    type
    provider
    url
    metadata
    creditCost
  }
}
"""

variables = {
    "input": {
        "type": "IMAGE",
        "provider": "flux-krea",
        "input": {
            "text": "A futuristic city with flying cars and neon lights"
        },
        "options": {
            "width": 1024,
            "height": 1024
        }
    }
}

response = requests.post(url, json={
    "query": query,
    "variables": variables
}, headers=headers)

data = response.json()
print("Result:", data["data"]["generate"])
mutation Generate($input: GenerateInput!) {
  generate(input: $input) {
    id
    status
    type
    provider
    url
    metadata
    creditCost
    createdAt
  }
}

# Variables
{
  "input": {
    "type": "IMAGE",
    "provider": "flux-krea",
    "input": {
      "text": "A futuristic city with flying cars and neon lights"
    },
    "options": {
      "width": 1024,
      "height": 1024,
      "version": "flux-krea",
      "quality": "high"
    }
  }
}

Pretschs

Flux Krea API utilisescha in model da pretschs basà sin credits. Ils credits vegnan consumads tenor la cumplexitad e la durada dal cuntegn generà.

Funcziun Credits Descripziun
Resoluziun standard 10-20 Credits 512x512 fin 1024x1024 pixels
Resoluziun auta 30-50 Credits 2048x2048 pixels e dapli

Endpoints da l'API

Flux Krea API è disponibel via noss endpoint da GraphQL unifitgà.

Endpoint GraphQL

POST https://api.doitong.com/graphql

Endpoint REST

POST https://api.doitong.com/v1/text_to_image

Parameters

Parameters disponibels per dumondas da Flux Krea API:

Parameter Tip Necessari Descripziun
service String Yes Identificader dal servetsch: "flux-krea"
prompt String Yes Descripziun textual dal cuntegn da generar
width Integer No Largezza da l'image en pixels (default: 1024)
height Integer No Altezza da l'image en pixels (default: 1024)
version String No Model version: "flux-krea"
webhookUrl String No URL per retschaver notificaziuns da cumplettaziun

Format da la resposta

Tut las respostas da l'API suondan in format consistent:

Resposta d'ina reussida

{
  "data": {
    "generateimage": {
      "id": "abc123xyz",
      "status": "processing",
      "url": null,
      "webhookUrl": "https://your-webhook.com/callback",
      "createdAt": "2024-01-01T00:00:00Z"
    }
  }
}

Resposta cumplettada

{
  "data": {
    "generateimage": {
      "id": "abc123xyz",
      "status": "completed",
      "url": "https://cdn.doitong.com/outputs/abc123xyz.jpg",
      "duration": null,
      "createdAt": "2024-01-01T00:00:00Z"
    }
  }
}

Gestiun d'errors

L'API dovra codes da status HTTP standards e returna missis d'error detagliads.

Codes d'error communabels

Code da status Tip d'error Descripziun
400 Bad Request Invalid parameters or malformed request
401 Unauthorized Missing or invalid API key
402 Payment Required Insufficient credits
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server error, please retry

Format da la resposta d'error

{
  "errors": [
    {
      "message": "Insufficient credits for this operation",
      "extensions": {
        "code": "INSUFFICIENT_CREDITS",
        "creditsRequired": 100,
        "creditsAvailable": 50
      }
    }
  ]
}

Webhooks

Reçave notificaziuns en temp real cur che la generaziun da tes text to image è cumplettada.

Configurar ils webhooks

Include a <code>webhookUrl</code> parameter in your request to receive a POST notification when processing is complete.

Payload dal webhook

{
  "id": "abc123xyz",
  "status": "completed",
  "url": "https://cdn.doitong.com/outputs/abc123xyz.jpg",
  "service": "flux-krea",
  "createdAt": "2024-01-01T00:00:00Z",
  "completedAt": "2024-01-01T00:01:00Z",
  "metadata": {
    "duration": null,
    "width": 1920,
    "height": 1080
  }
}

Segirezza dals webhooks

Tut las dumondas da webhooks includan in header da signatura per la verificaziun:

X-Doitong-Signature: sha256=abc123...

Limits da rata

Per garantir in'utilisaziun faira e la stabilitad dal sistem, s'applitgan ils suandants limits da rata:

Plan Dumondas/Minuta Jobs simultans Limit dadiari
Gratuit 10 1 100
Starter 30 3 1,000
Pro 60 10 10,000
Enterprise Persunalisà Persunalisà Illimità
Headers dals limits da rata: Controllescha ils headers da resposta per il status actual dal limit:
  • X-RateLimit-Limit: Maximum requests per window
  • X-RateLimit-Remaining: Requests remaining
  • X-RateLimit-Reset: Window reset timestamp

Best Practices

1. Optimisescha tes prompts

Scriva prompts clers e descriptivs per ils megliers resultats:

  • Be specific about visual elements, style, and mood
  • Include details about lighting, camera angles, and composition
  • Avoid contradictory or impossible requests

2. Gestescha il processament asincron

La generaziun è asincrona. Implementescha in polling u webhooks adequats:

// Polling example
async function pollStatus(jobId) {
  let status = 'processing';
  while (status === 'processing') {
    await sleep(2000); // Wait 2 seconds
    const result = await checkJobStatus(jobId);
    status = result.status;
  }
  return result;
}

3. Recunvengia d'errors

Implementescha ina logica da retry cun exponential backoff:

async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000);
    }
  }
}

4. Monitorisescha il consum da credits

Controllescha tes consum da credits per evitar interrupziuns:

  • Check credit balance before large batch operations
  • Set up alerts for low credit thresholds
  • Implement credit-aware request queuing

Pront per cumenzar?

S'uniescha a millis da sviluppaders che dovran Flux Krea API per crear cuntegn ustrius

Obtegnair la clav d'API Vair ils pretschs