Back to Integrations

Contentful Integration

CMS

Headless CMS image processing

Contentful Webhook Handler

Auto-Enhance on Asset Publish
// Contentful Webhook Handler (Next.js API Route)
import { createClient } from 'contentful-management';

const client = createClient({
  accessToken: 'YOUR_CONTENTFUL_MANAGEMENT_TOKEN'
});

export async function POST(req) {
  const { sys, fields } = await req.json();
  
  // Only process asset publish events
  if (sys.type !== 'Asset') {
    return Response.json({ skipped: true });
  }
  
  const imageUrl = `https:${fields.file['en-US'].url}`;
  
  // Enhance with ButterflyAPI
  const enhanced = await fetch('https://butterflyapi.com/api/v1/run', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_BUTTERFLY_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      api: 'image-enhance',
      input: { image_url: imageUrl, scale: 2 }
    })
  }).then(r => r.json());
  
  // Generate caption
  const caption = await fetch('https://butterflyapi.com/api/v1/run', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_BUTTERFLY_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      api: 'image-caption',
      input: { image_url: imageUrl }
    })
  }).then(r => r.json());
  
  // Update asset description with caption
  const space = await client.getSpace('YOUR_CONTENTFUL_SPACE_ID');
  const env = await space.getEnvironment('master');
  const asset = await env.getAsset(sys.id);
  
  asset.fields.description = { 'en-US': caption.output.caption };
  await asset.update();
  
  return Response.json({ 
    enhanced: enhanced.output.image_url,
    caption: caption.output.caption 
  });
}