Examples
Real-world examples for common FloImg API operations.
Execute a Workflow
Section titled “Execute a Workflow”const response = await fetch('https://api.floimg.com/v1/workflows/execute', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.FLOIMG_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ workflowId: 'wf_abc123', parameters: { prompt: 'A serene mountain landscape at sunset', width: 1200, height: 630, }, }),});
const result = await response.json();console.log(result.output.url);// https://storage.floimg.com/images/xyz789.pngimport requestsimport os
response = requests.post( 'https://api.floimg.com/v1/workflows/execute', headers={ 'Authorization': f'Bearer {os.environ["FLOIMG_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'workflowId': 'wf_abc123', 'parameters': { 'prompt': 'A serene mountain landscape at sunset', 'width': 1200, 'height': 630, }, },)
result = response.json()print(result['output']['url'])curl -X POST https://api.floimg.com/v1/workflows/execute \ -H "Authorization: Bearer $FLOIMG_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "workflowId": "wf_abc123", "parameters": { "prompt": "A serene mountain landscape at sunset", "width": 1200, "height": 630 } }'Upload an Image
Section titled “Upload an Image”import { createReadStream } from 'fs';import FormData from 'form-data';
const form = new FormData();form.append('file', createReadStream('./image.png'));form.append('projectId', 'proj_abc123');
const response = await fetch('https://api.floimg.com/v1/storage/upload', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.FLOIMG_API_KEY}`, }, body: form,});
const result = await response.json();console.log(result.url);// https://storage.floimg.com/images/abc123.pngimport requestsimport os
with open('./image.png', 'rb') as f: response = requests.post( 'https://api.floimg.com/v1/storage/upload', headers={ 'Authorization': f'Bearer {os.environ["FLOIMG_API_KEY"]}', }, files={'file': f}, data={'projectId': 'proj_abc123'}, )
result = response.json()print(result['url'])curl -X POST https://api.floimg.com/v1/storage/upload \ -H "Authorization: Bearer $FLOIMG_API_KEY" \ -F "file=@./image.png" \ -F "projectId=proj_abc123"Async Workflow Execution
Section titled “Async Workflow Execution”For long-running workflows, use async execution:
// Start async executionconst startResponse = await fetch('https://api.floimg.com/v1/workflows/execute', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.FLOIMG_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ workflowId: 'wf_abc123', parameters: { prompt: 'A detailed illustration' }, async: true, }),});
const { executionId } = await startResponse.json();
// Poll for completionconst pollExecution = async (id: string): Promise<any> => { const response = await fetch( `https://api.floimg.com/v1/workflows/executions/${id}`, { headers: { 'Authorization': `Bearer ${process.env.FLOIMG_API_KEY}`, }, } );
const result = await response.json();
if (result.status === 'pending' || result.status === 'running') { await new Promise(r => setTimeout(r, 1000)); return pollExecution(id); }
return result;};
const result = await pollExecution(executionId);console.log(result.output.url);import requestsimport timeimport os
# Start async executionstart_response = requests.post( 'https://api.floimg.com/v1/workflows/execute', headers={ 'Authorization': f'Bearer {os.environ["FLOIMG_API_KEY"]}', 'Content-Type': 'application/json', }, json={ 'workflowId': 'wf_abc123', 'parameters': {'prompt': 'A detailed illustration'}, 'async': True, },)
execution_id = start_response.json()['executionId']
# Poll for completiondef poll_execution(exec_id): while True: response = requests.get( f'https://api.floimg.com/v1/workflows/executions/{exec_id}', headers={ 'Authorization': f'Bearer {os.environ["FLOIMG_API_KEY"]}', }, ) result = response.json()
if result['status'] in ['pending', 'running']: time.sleep(1) continue
return result
result = poll_execution(execution_id)print(result['output']['url'])Error Handling
Section titled “Error Handling”async function executeWorkflow(workflowId: string, parameters: object) { const response = await fetch('https://api.floimg.com/v1/workflows/execute', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.FLOIMG_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ workflowId, parameters }), });
if (!response.ok) { const error = await response.json();
switch (error.error.code) { case 'rate_limited': const retryAfter = response.headers.get('Retry-After'); throw new Error(`Rate limited. Retry after ${retryAfter}s`);
case 'unauthorized': throw new Error('Invalid API key');
case 'not_found': throw new Error('Workflow not found');
default: throw new Error(error.error.message); } }
return response.json();}import requestsimport os
def execute_workflow(workflow_id, parameters): response = requests.post( 'https://api.floimg.com/v1/workflows/execute', headers={ 'Authorization': f'Bearer {os.environ["FLOIMG_API_KEY"]}', 'Content-Type': 'application/json', }, json={'workflowId': workflow_id, 'parameters': parameters}, )
if not response.ok: error = response.json() code = error['error']['code']
if code == 'rate_limited': retry_after = response.headers.get('Retry-After') raise Exception(f'Rate limited. Retry after {retry_after}s') elif code == 'unauthorized': raise Exception('Invalid API key') elif code == 'not_found': raise Exception('Workflow not found') else: raise Exception(error['error']['message'])
return response.json()Batch Processing with Rate Limit Handling
Section titled “Batch Processing with Rate Limit Handling”async function batchExecute( workflowId: string, items: object[], concurrency = 5) { const results = []; const queue = [...items];
const worker = async () => { while (queue.length > 0) { const item = queue.shift(); if (!item) break;
try { const result = await executeWithRetry( () => executeWorkflow(workflowId, item) ); results.push({ success: true, data: result }); } catch (error) { results.push({ success: false, error }); } } };
// Run workers in parallel await Promise.all( Array(concurrency).fill(null).map(() => worker()) );
return results;}
async function executeWithRetry(fn: () => Promise<any>, maxRetries = 3) { let delay = 1000;
for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error: any) { if (error.message.includes('Rate limited') && i < maxRetries - 1) { await new Promise(r => setTimeout(r, delay)); delay *= 2; continue; } throw error; } }}
// Usageconst results = await batchExecute('wf_abc123', [ { prompt: 'Image 1' }, { prompt: 'Image 2' }, { prompt: 'Image 3' },]);Next Steps
Section titled “Next Steps”- Authentication - API key setup
- Endpoints - Full endpoint reference
- Rate Limits - Understanding limits