# Build APIs with AI—No Coding Required

> Generate a production-ready Aerostack API from a plain-English description or screenshot. No coding required — the AI writes the backend for you.

Aerostack's **AI API Generator** transforms your ideas into production-ready code in minutes. Describe what you need in plain English, upload mockups, or share screenshots—our AI does the rest.

## How It Works

1. **Describe Your Need** — Tell the AI what your API should do in plain English
2. **AI Analyzes** — AI asks clarifying questions and recommends infrastructure
3. **Code Generated** — Production-ready code with caching, error handling, validation
4. **Review and Deploy** — Customize if needed, then deploy with one click

## Smart Infrastructure Recommendations

The AI doesn't just write code—it **recommends the right infrastructure** for your use case:

- **Cache** — For expensive computations, frequently accessed data
- **Queue** — For long-running tasks, background processing, async workflows
- **Storage** — For file uploads, image processing, document management
- **AI Models** — For content moderation, classification, recommendations
- **Database** — Optimized queries with proper indexing

---

## Example 1: Product Search API

**Your Prompt:**
> "I need an API to search products by name and category with results sorted by popularity"

**AI Response:**
```
I'll create a product search API for you. Based on your requirements, I recommend:

✓ Cache: Store search results (TTL: 1 hour)
✓ Database: Query products table with indexed columns
✓ Pagination: Support limit/offset for large result sets

Here's your API:
```

```javascript

  const { query, category, page = 1, limit = 20 } = event.data;
  
  // Validate inputs
  if (!query || query.length < 2) {
    throw new Error('Query must be at least 2 characters');
  }
  
  const offset = (page - 1) * limit;
  const cacheKey = `search:${query}:${category}:${page}`;
  
  // Check cache first
  const cached = await sdk.cache.get(cacheKey);
  if (cached) return cached;
  
  // Query database with popularity sorting
  const products = await sdk.db.query(`
    SELECT id, name, slug, price, image_url, category
    FROM products 
    WHERE name LIKE ? 
      AND category = ? 
      AND is_active = 1
    ORDER BY view_count DESC, created_at DESC
    LIMIT ? OFFSET ?
  `, [`%${query}%`, category, limit, offset]);
  
  // Get total count for pagination
  const [{ total }] = await sdk.db.query(`
    SELECT COUNT(*) as total 
    FROM products 
    WHERE name LIKE ? AND category = ?
  `, [`%${query}%`, category]);
  
  const result = {
    results: products,
    pagination: {
      page,
      limit,
      total,
      pages: Math.ceil(total / limit)
    }
  };
  
  // Cache for 1 hour
  await sdk.cache.set(cacheKey, result, 3600);
  
  return result;
}
```

**Time to deploy:** 2 minutes

---

## Example 2: Image Upload and Thumbnail Generation

**Your Prompt:**
> "Users should be able to upload profile pictures and I need to create thumbnails"

**AI Response:**
```
I'll build an image upload API with thumbnail generation. This requires:

✓ Storage: Save original images and thumbnails
✓ Queue: Process images asynchronously (can take 5-10 seconds)
✓ Database: Track upload status and file URLs

Here's your upload API:
```

```javascript

  const { user_id, image_base64, filename } = event.data;
  
  // Validate image
  if (!image_base64 || !user_id) {
    throw new Error('user_id and image_base64 are required');
  }
  
  // Generate unique filename
  const timestamp = Date.now();
  const originalKey = `profiles/${user_id}/original_${timestamp}_${filename}`;
  const thumbnailKey = `profiles/${user_id}/thumb_${timestamp}_${filename}`;
  
  // Upload original image
  const originalUrl = await sdk.storage.upload(originalKey, image_base64, {
    contentType: 'image/jpeg'
  });
  
  // Enqueue thumbnail generation job
  await sdk.queue.enqueue('generate-thumbnail', {
    originalKey,
    thumbnailKey,
    user_id,
    max_width: 200,
    max_height: 200
  });
  
  // Save to database
  const upload = await sdk.db.query(`
    INSERT INTO uploads (user_id, original_url, thumbnail_url, status, created_at)
    VALUES (?, ?, ?, 'processing', ?)
  `, [user_id, originalUrl, null, timestamp]);
  
  return {
    upload_id: upload.lastInsertRowid,
    original_url: originalUrl,
    status: 'processing',
    message: 'Image uploaded. Thumbnail will be ready in a few seconds.'
  };
}
```

**Background Worker** (auto-generated):
```javascript
// This runs automatically when queue job is triggered

  const { originalKey, thumbnailKey, user_id } = job.data;
  
  // Download original
  const originalImage = await sdk.storage.download(originalKey);
  
  // Resize image (using built-in image processing)
  const thumbnail = await sdk.image.resize(originalImage, {
    width: 200,
    height: 200,
    fit: 'cover'
  });
  
  // Upload thumbnail
  const thumbnailUrl = await sdk.storage.upload(thumbnailKey, thumbnail, {
    contentType: 'image/jpeg'
  });
  
  // Update database
  await sdk.db.query(`
    UPDATE uploads 
    SET thumbnail_url = ?, status = 'completed'
    WHERE user_id = ? AND original_url = ?
  `, [thumbnailUrl, user_id, originalImage.url]);
  
  return { success: true, thumbnailUrl };
}
```

---

## Example 3: User Recommendations Engine

**Your Prompt + Wireframe:**
> "I need personalized product recommendations based on user purchase history" 
> *[uploads wireframe showing recommendation cards]*

**AI Response:**
```
I'll create a recommendations API using AI for personalization. Based on your wireframe and requirements:

✓ AI Model: Use collaborative filtering for recommendations
✓ Cache: Store computed recommendations (refresh daily)
✓ Database: Query purchase history and product catalog
✓ Pagination: Return 10 recommendations per request

Here's your API:
```

```javascript

  const { user_id, limit = 10 } = event.data;
  
  const cacheKey = `recommendations:${user_id}`;
  
  // Check cache first (recommendations updated daily)
  const cached = await sdk.cache.get(cacheKey);
  if (cached) return cached;
  
  // Get user's purchase history
  const purchases = await sdk.db.query(`
    SELECT p.id, p.name, p.category, p.tags, o.created_at
    FROM orders o
    JOIN products p ON o.product_id = p.id
    WHERE o.user_id = ?
    ORDER BY o.created_at DESC
    LIMIT 50
  `, [user_id]);
  
  if (purchases.length === 0) {
    // New user: return popular products
    return await getPopularProducts(sdk, limit);
  }
  
  // Use AI to generate personalized recommendations
  const prompt = `
    User purchase history: ${JSON.stringify(purchases)}
    
    Recommend ${limit} products this user might like based on their purchase patterns.
    Consider: similar categories, complementary products, trending items.
    Return product IDs as comma-separated numbers.
  `;
  
  const aiResponse = await sdk.ai.chat('@cf/meta/llama-3-8b-instruct', [
    {
      role: 'system',
      content: 'You are a recommendation engine. Analyze purchase patterns and suggest relevant products.'
    },
    {
      role: 'user',
      content: prompt
    }
  ]);
  
  // Parse AI response to get product IDs
  const recommendedIds = aiResponse.split(',').map(id => parseInt(id.trim()));
  
  // Fetch full product details
  const recommendations = await sdk.db.query(`
    SELECT id, name, slug, price, image_url, rating
    FROM products
    WHERE id IN (${recommendedIds.join(',')})
    AND is_active = 1
    LIMIT ?
  `, [limit]);
  
  // Cache for 24 hours
  await sdk.cache.set(cacheKey, recommendations, 86400);
  
  return { recommendations };
}

async function getPopularProducts(sdk, limit) {
  const popular = await sdk.db.query(`
    SELECT id, name, slug, price, image_url, rating
    FROM products
    WHERE is_active = 1
    ORDER BY view_count DESC, rating DESC
    LIMIT ?
  `, [limit]);
  
  return { recommendations: popular };
}
```

---

## AI Understands Visual Context

Upload screenshots, wireframes, or mockups and the AI will:
- Extract UI requirements automatically
- Suggest appropriate data structures
- Generate APIs that match your interface design
- Recommend pagination, filters, and sorting based on your UI

**Example:** Upload a screenshot of a product grid → AI generates search, filter, and sort APIs with proper pagination.

---

## Best Practices

The AI automatically implements:
- ✅ **Input Validation** — Checks for required fields, type safety
- ✅ **Error Handling** — Graceful errors with helpful messages
- ✅ **Caching Strategy** — Recommends appropriate TTL based on data volatility
- ✅ **Pagination** — For endpoints that return lists
- ✅ **Rate Limiting** — Protects against abuse
- ✅ **Security** — SQL injection prevention, input sanitization

---

## Try It Now

Head to the Logic Lab in your admin dashboard and click "Create with AI":

  

---

## Next Steps

- [Custom APIs and SDK](/sdk) — Write code directly with SDK
- [Hooks and Events](/features/hooks) — Customize API behavior
- [SDK Reference](/sdk) — Explore all SDK methods
