Free Presentation Generation via API: Complete Guide to MagicSlides API Integration

Free Presentation Generation via API: Complete Guide to MagicSlides API Integration

Creating presentations manually can be time-consuming and repetitive, especially when you need to generate multiple slides from similar content types. What if you could automate this entire process with just a few lines of code? Enter the MagicSlides API – a powerful solution that transforms topics, summaries, and YouTube videos into professional presentations within seconds.

In this comprehensive guide, we'll explore how to integrate MagicSlides API into your applications, covering implementation examples in multiple programming languages and real-world use cases that can revolutionize your workflow.

What is MagicSlides API?

MagicSlides API is a RESTful service that leverages artificial intelligence to automatically generate presentation slides from various content sources. Whether you have a topic idea, a detailed summary, or a YouTube video URL, the API can transform it into a professional PowerPoint presentation in under 3 seconds.

Key Features:

  • AI-Powered Generation: Uses advanced AI to create contextually relevant slides
  • Multiple Input Types: Supports topics, summaries, and YouTube videos
  • Fast Processing: Generates presentations in 2-3 seconds
  • Customizable Slide Count: Optional parameter to control presentation length
  • Professional Templates: Auto-formatted slides with modern design
  • Easy Integration: Simple REST API with JSON requests/responses

API Endpoints Overview

The MagicSlides API provides three main endpoints for different content types:

1. Topic to Presentation

Endpoint: https://magicslides-tools-api.onrender.com/public/api/ppt_from_topic Method: POST

Perfect for generating presentations from a single topic with optional additional context.

2. Summary to Presentation

Endpoint: https://magicslides-tools-api.onrender.com/public/api/ppt_from_summery Method: POST

Ideal for converting detailed text content or summaries into structured presentations.

3. YouTube to Presentation

Endpoint: https://magicslides-tools-api.onrender.com/public/api/ppt_from_youtube Method: POST

Transforms YouTube videos into presentation slides by analyzing video content.

Getting Started: Your Access Credentials

To use the MagicSlides API, you'll need:

  • Email: Your registered email address
  • Access ID: Your unique API access identifier (e.g., ae03501c-b3c2-436e-bf25-74de5b921716)

Implementation Examples

Let's explore how to integrate MagicSlides API across different programming languages:

1. Node.js Implementation

const axios = require('axios');

class MagicSlidesAPI {
  constructor(email, accessId) {
    this.email = email;
    this.accessId = accessId;
    this.baseURL = 'https://magicslides-tools-api.onrender.com/public/api';
  }

  // Generate presentation from topic
  async createFromTopic(topic, extraInfoSource = '', slideCount = null) {
    try {
      const response = await axios.post(`${this.baseURL}/ppt_from_topic`, {
        topic,
        extraInfoSource,
        email: this.email,
        accessId: this.accessId,
        slideCount
      });
      return response.data;
    } catch (error) {
      throw new Error(`Topic to PPT Error: ${error.response?.data || error.message}`);
    }
  }

  // Generate presentation from summary
  async createFromSummary(summaryText, slideCount = null) {
    try {
      const response = await axios.post(`${this.baseURL}/ppt_from_summery`, {
        msSummaryText: summaryText,
        email: this.email,
        accessId: this.accessId,
        slideCount
      });
      return response.data;
    } catch (error) {
      throw new Error(`Summary to PPT Error: ${error.response?.data || error.message}`);
    }
  }

  // Generate presentation from YouTube video
  async createFromYouTube(youtubeURL, slideCount = null) {
    try {
      const response = await axios.post(`${this.baseURL}/ppt_from_youtube`, {
        youtubeURL,
        email: this.email,
        accessId: this.accessId,
        slideCount
      });
      return response.data;
    } catch (error) {
      throw new Error(`YouTube to PPT Error: ${error.response?.data || error.message}`);
    }
  }
}

// Usage Example
const magicSlides = new MagicSlidesAPI('your-email@example.com', 'your-access-id');

// Generate from topic
magicSlides.createFromTopic('Artificial Intelligence in Healthcare', 'Focus on machine learning applications')
  .then(result => console.log('Presentation URL:', result.url))
  .catch(error => console.error(error));

// Generate from YouTube video
magicSlides.createFromYouTube('https://www.youtube.com/watch?v=example')
  .then(result => console.log('Presentation URL:', result.url))
  .catch(error => console.error(error));

2. Python Implementation

import requests
import json

class MagicSlidesAPI:
    def __init__(self, email, access_id):
        self.email = email
        self.access_id = access_id
        self.base_url = "https://magicslides-tools-api.onrender.com/public/api"
    
    def create_from_topic(self, topic, extra_info_source="", slide_count=None):
        """Generate presentation from topic"""
        url = f"{self.base_url}/ppt_from_topic"
        payload = {
            "topic": topic,
            "extraInfoSource": extra_info_source,
            "email": self.email,
            "accessId": self.access_id
        }
        if slide_count:
            payload["slideCount"] = slide_count
            
        try:
            response = requests.post(url, json=payload)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"Topic to PPT Error: {e}")
    
    def create_from_summary(self, summary_text, slide_count=None):
        """Generate presentation from summary"""
        url = f"{self.base_url}/ppt_from_summery"
        payload = {
            "msSummaryText": summary_text,
            "email": self.email,
            "accessId": self.access_id
        }
        if slide_count:
            payload["slideCount"] = slide_count
            
        try:
            response = requests.post(url, json=payload)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"Summary to PPT Error: {e}")
    
    def create_from_youtube(self, youtube_url, slide_count=None):
        """Generate presentation from YouTube video"""
        url = f"{self.base_url}/ppt_from_youtube"
        payload = {
            "youtubeURL": youtube_url,
            "email": self.email,
            "accessId": self.access_id
        }
        if slide_count:
            payload["slideCount"] = slide_count
            
        try:
            response = requests.post(url, json=payload)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"YouTube to PPT Error: {e}")

# Usage Example
magic_slides = MagicSlidesAPI("your-email@example.com", "your-access-id")

try:
    # Generate from topic
    result = magic_slides.create_from_topic(
        "Climate Change Solutions", 
        "Focus on renewable energy technologies"
    )
    print(f"Presentation URL: {result['url']}")
    
    # Generate from summary
    summary = """
    Machine learning is revolutionizing healthcare through predictive analytics,
    diagnostic imaging, drug discovery, and personalized treatment plans.
    Key applications include early disease detection and treatment optimization.
    """
    result = magic_slides.create_from_summary(summary, slide_count=8)
    print(f"Presentation URL: {result['url']}")
    
except Exception as e:
    print(f"Error: {e}")

3. PHP Implementation

<?php

class MagicSlidesAPI {
    private $email;
    private $accessId;
    private $baseURL = 'https://magicslides-tools-api.onrender.com/public/api';
    
    public function __construct($email, $accessId) {
        $this->email = $email;
        $this->accessId = $accessId;
    }
    
    private function makeRequest($endpoint, $data) {
        $url = $this->baseURL . $endpoint;
        $data['email'] = $this->email;
        $data['accessId'] = $this->accessId;
        
        $options = [
            'http' => [
                'header' => "Content-type: application/json\r\n",
                'method' => 'POST',
                'content' => json_encode($data)
            ]
        ];
        
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        
        if ($result === FALSE) {
            throw new Exception("API request failed");
        }
        
        return json_decode($result, true);
    }
    
    public function createFromTopic($topic, $extraInfoSource = '', $slideCount = null) {
        $data = [
            'topic' => $topic,
            'extraInfoSource' => $extraInfoSource
        ];
        
        if ($slideCount !== null) {
            $data['slideCount'] = $slideCount;
        }
        
        return $this->makeRequest('/ppt_from_topic', $data);
    }
    
    public function createFromSummary($summaryText, $slideCount = null) {
        $data = [
            'msSummaryText' => $summaryText
        ];
        
        if ($slideCount !== null) {
            $data['slideCount'] = $slideCount;
        }
        
        return $this->makeRequest('/ppt_from_summery', $data);
    }
    
    public function createFromYouTube($youtubeURL, $slideCount = null) {
        $data = [
            'youtubeURL' => $youtubeURL
        ];
        
        if ($slideCount !== null) {
            $data['slideCount'] = $slideCount;
        }
        
        return $this->makeRequest('/ppt_from_youtube', $data);
    }
}

// Usage Example
try {
    $magicSlides = new MagicSlidesAPI('your-email@example.com', 'your-access-id');
    
    // Generate from topic
    $result = $magicSlides->createFromTopic(
        'Digital Marketing Strategies', 
        'Focus on social media and content marketing'
    );
    echo "Presentation URL: " . $result['url'] . "\n";
    
    // Generate from YouTube
    $result = $magicSlides->createFromYouTube('https://www.youtube.com/watch?v=example');
    echo "Presentation URL: " . $result['url'] . "\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

?>

4. cURL Implementation (Command Line)

#!/bin/bash

# Configuration
EMAIL="your-email@example.com"
ACCESS_ID="your-access-id"
BASE_URL="https://magicslides-tools-api.onrender.com/public/api"

# Function to create presentation from topic
create_from_topic() {
    local topic="$1"
    local extra_info="$2"
    
    curl -X POST "${BASE_URL}/ppt_from_topic" \
         -H "Content-Type: application/json" \
         -d "{
             \"topic\": \"$topic\",
             \"extraInfoSource\": \"$extra_info\",
             \"email\": \"$EMAIL\",
             \"accessId\": \"$ACCESS_ID\"
         }"
}

# Function to create presentation from summary
create_from_summary() {
    local summary="$1"
    
    curl -X POST "${BASE_URL}/ppt_from_summery" \
         -H "Content-Type: application/json" \
         -d "{
             \"msSummaryText\": \"$summary\",
             \"email\": \"$EMAIL\",
             \"accessId\": \"$ACCESS_ID\"
         }"
}

# Function to create presentation from YouTube
create_from_youtube() {
    local youtube_url="$1"
    
    curl -X POST "${BASE_URL}/ppt_from_youtube" \
         -H "Content-Type: application/json" \
         -d "{
             \"youtubeURL\": \"$youtube_url\",
             \"email\": \"$EMAIL\",
             \"accessId\": \"$ACCESS_ID\"
         }"
}

# Usage examples
echo "Creating presentation from topic..."
create_from_topic "Blockchain Technology" "Focus on cryptocurrency and smart contracts"

echo -e "\n\nCreating presentation from YouTube..."
create_from_youtube "https://www.youtube.com/watch?v=example"

echo -e "\n\nCreating presentation from summary..."
create_from_summary "Artificial Intelligence is transforming industries through automation, machine learning, and data analysis. Key benefits include increased efficiency, improved decision-making, and cost reduction."

Real-World Use Cases

1. Educational Platform Integration

Transform your e-learning platform by automatically generating course presentations:

// Example: LMS Integration
class LMSPresentationGenerator {
  constructor(magicSlidesAPI) {
    this.api = magicSlidesAPI;
  }
  
  async generateCourseSlides(courseContent) {
    const presentations = [];
    
    for (const lesson of courseContent.lessons) {
      try {
        const result = await this.api.createFromSummary(
          lesson.summary, 
          lesson.targetSlideCount || 10
        );
        
        presentations.push({
          lessonId: lesson.id,
          title: lesson.title,
          presentationUrl: result.url,
          createdAt: new Date()
        });
        
        // Save to database
        await this.savePresentationToDatabase(lesson.id, result.url);
        
      } catch (error) {
        console.error(`Failed to generate slides for lesson ${lesson.id}:`, error);
      }
    }
    
    return presentations;
  }
  
  async savePresentationToDatabase(lessonId, presentationUrl) {
    // Database implementation here
    console.log(`Saved presentation for lesson ${lessonId}: ${presentationUrl}`);
  }
}

2. Content Management System Plugin

Create a WordPress plugin that generates presentations from blog posts:

<?php
// WordPress Plugin: Auto Presentation Generator

class AutoPresentationPlugin {
    private $magicSlides;
    
    public function __construct() {
        $this->magicSlides = new MagicSlidesAPI(
            get_option('magicslides_email'),
            get_option('magicslides_access_id')
        );
        
        add_action('publish_post', array($this, 'generatePresentationFromPost'));
        add_meta_box('presentation_generator', 'Generate Presentation', 
                    array($this, 'presentationMetaBox'), 'post');
    }
    
    public function generatePresentationFromPost($postId) {
        $post = get_post($postId);
        $content = strip_tags($post->post_content);
        
        if (strlen($content) > 100) {
            try {
                $result = $this->magicSlides->createFromSummary($content);
                update_post_meta($postId, 'presentation_url', $result['url']);
                
                // Notify admin
                wp_mail(
                    get_option('admin_email'),
                    'Presentation Generated',
                    "Presentation created for post: {$post->post_title}\nURL: {$result['url']}"
                );
                
            } catch (Exception $e) {
                error_log("Presentation generation failed for post {$postId}: " . $e->getMessage());
            }
        }
    }
    
    public function presentationMetaBox($post) {
        $presentationUrl = get_post_meta($post->ID, 'presentation_url', true);
        
        if ($presentationUrl) {
            echo "<p><strong>Generated Presentation:</strong></p>";
            echo "<p><a href='{$presentationUrl}' target='_blank'>View Presentation</a></p>";
        } else {
            echo "<p>No presentation generated yet.</p>";
            echo "<button type='button' onclick='generatePresentation({$post->ID})'>Generate Now</button>";
        }
    }
}

new AutoPresentationPlugin();
?>

3. Slack Bot for Team Productivity

Enhance team collaboration with automatic presentation generation:

const { App } = require('@slack/bolt');

class SlackPresentationBot {
  constructor(slackToken, magicSlidesAPI) {
    this.app = new App({
      token: slackToken,
      socketMode: true
    });
    
    this.magicSlides = magicSlidesAPI;
    this.setupCommands();
  }
  
  setupCommands() {
    // Slash command: /generate-slides [topic]
    this.app.command('/generate-slides', async ({ command, ack, respond }) => {
      await ack();
      
      const topic = command.text;
      if (!topic) {
        await respond('Please provide a topic. Usage: /generate-slides Your Topic Here');
        return;
      }
      
      try {
        await respond(`🔄 Generating presentation for: "${topic}"`);
        
        const result = await this.magicSlides.createFromTopic(topic);
        
        await respond({
          text: `✅ Presentation generated successfully!`,
          blocks: [
            {
              type: 'section',
              text: {
                type: 'mrkdwn',
                text: `*Topic:* ${topic}\n*Generated:* ${new Date().toLocaleString()}`
              }
            },
            {
              type: 'actions',
              elements: [
                {
                  type: 'button',
                  text: {
                    type: 'plain_text',
                    text: 'View Presentation'
                  },
                  url: result.url,
                  action_id: 'view_presentation'
                }
              ]
            }
          ]
        });
        
      } catch (error) {
        await respond(`❌ Failed to generate presentation: ${error.message}`);
      }
    });
    
    // Listen for YouTube links in messages
    this.app.message(/https:\/\/(www\.)?youtube\.com\/watch\?v=[\w-]+/, async ({ message, say }) => {
      const youtubeUrl = message.text.match(/https:\/\/(www\.)?youtube\.com\/watch\?v=[\w-]+/)[0];
      
      try {
        await say(`🔄 Generating presentation from YouTube video...`);
        
        const result = await this.magicSlides.createFromYouTube(youtubeUrl);
        
        await say({
          text: '✅ YouTube presentation generated!',
          blocks: [
            {
              type: 'section',
              text: {
                type: 'mrkdwn',
                text: `*Source:* <${youtubeUrl}|YouTube Video>\n*Generated:* ${new Date().toLocaleString()}`
              }
            },
            {
              type: 'actions',
              elements: [
                {
                  type: 'button',
                  text: {
                    type: 'plain_text',
                    text: 'View Presentation'
                  },
                  url: result.url,
                  action_id: 'view_presentation'
                }
              ]
            }
          ]
        });
        
      } catch (error) {
        await say(`❌ Failed to generate presentation: ${error.message}`);
      }
    });
  }
  
  async start() {
    await this.app.start();
    console.log('⚡️ Slack Presentation Bot is running!');
  }
}

// Usage
const magicSlides = new MagicSlidesAPI('your-email@example.com', 'your-access-id');
const bot = new SlackPresentationBot(process.env.SLACK_BOT_TOKEN, magicSlides);
bot.start();

4. Automated Social Media Content Creation

Transform social media content into presentations for multiple platforms:

import schedule
import time
from datetime import datetime

class SocialMediaPresentationGenerator:
    def __init__(self, magic_slides_api):
        self.api = magic_slides_api
        self.content_queue = []
    
    def add_content_to_queue(self, content_type, content_data, platform):
        """Add content to generation queue"""
        self.content_queue.append({
            'type': content_type,
            'data': content_data,
            'platform': platform,
            'timestamp': datetime.now()
        })
    
    def process_content_queue(self):
        """Process all queued content"""
        for content in self.content_queue:
            try:
                presentation_url = None
                
                if content['type'] == 'topic':
                    result = self.api.create_from_topic(
                        content['data']['topic'],
                        content['data'].get('extra_info', ''),
                        slide_count=5  # Shorter for social media
                    )
                    presentation_url = result['url']
                    
                elif content['type'] == 'youtube':
                    result = self.api.create_from_youtube(
                        content['data']['url'],
                        slide_count=6
                    )
                    presentation_url = result['url']
                
                if presentation_url:
                    self.post_to_social_media(
                        content['platform'],
                        presentation_url,
                        content['data']
                    )
                    
            except Exception as e:
                print(f"Error processing content: {e}")
        
        # Clear processed queue
        self.content_queue = []
    
    def post_to_social_media(self, platform, presentation_url, content_data):
        """Post generated presentation to social media platforms"""
        if platform == 'linkedin':
            self.post_to_linkedin(presentation_url, content_data)
        elif platform == 'twitter':
            self.post_to_twitter(presentation_url, content_data)
        elif platform == 'facebook':
            self.post_to_facebook(presentation_url, content_data)
    
    def post_to_linkedin(self, presentation_url, content_data):
        """Post to LinkedIn with professional formatting"""
        message = f"""
🎯 New Presentation: {content_data.get('title', 'Professional Insights')}

📊 Key highlights covered in this presentation:
✅ Industry best practices
✅ Actionable insights
✅ Data-driven recommendations

View the full presentation: {presentation_url}

#ProfessionalDevelopment #BusinessInsights #Leadership
        """
        # LinkedIn API integration here
        print(f"Posted to LinkedIn: {message}")
    
    def post_to_twitter(self, presentation_url, content_data):
        """Post to Twitter with hashtags"""
        message = f"""
🚀 New presentation available: {content_data.get('title', 'Latest Insights')}

Quick, actionable insights in slide format 📊

Check it out: {presentation_url}

#Presentation #Learning #Growth
        """
        # Twitter API integration here
        print(f"Posted to Twitter: {message}")
    
    def post_to_facebook(self, presentation_url, content_data):
        """Post to Facebook with engaging format"""
        message = f"""
📖 Fresh insights in our latest presentation!

Topic: {content_data.get('title', 'Educational Content')}

Perfect for quick learning and sharing with your team 🎯

Access here: {presentation_url}
        """
        # Facebook API integration here
        print(f"Posted to Facebook: {message}")
    
    def schedule_daily_content(self):
        """Schedule daily content generation"""
        # Add trending topics
        trending_topics = [
            {"topic": "AI in Business 2025", "extra_info": "Focus on practical applications"},
            {"topic": "Remote Work Best Practices", "extra_info": "Productivity and collaboration"},
            {"topic": "Digital Marketing Trends", "extra_info": "Latest strategies and tools"}
        ]
        
        for topic_data in trending_topics:
            self.add_content_to_queue('topic', topic_data, 'linkedin')
        
        self.process_content_queue()

# Usage and Scheduling
magic_slides = MagicSlidesAPI("your-email@example.com", "your-access-id")
social_generator = SocialMediaPresentationGenerator(magic_slides)

# Schedule daily content generation
schedule.every().day.at("09:00").do(social_generator.schedule_daily_content)

# Add manual content
social_generator.add_content_to_queue(
    'youtube',
    {
        'url': 'https://www.youtube.com/watch?v=tech-talk-example',
        'title': 'Latest Tech Insights'
    },
    'twitter'
)

# Run scheduler
while True:
    schedule.run_pending()
    time.sleep(60)

Best Practices and Tips

1. Error Handling

Always implement robust error handling for API calls:

async function generatePresentationSafely(api, type, data) {
  const maxRetries = 3;
  let attempt = 0;
  
  while (attempt < maxRetries) {
    try {
      let result;
      
      switch (type) {
        case 'topic':
          result = await api.createFromTopic(data.topic, data.extraInfo);
          break;
        case 'summary':
          result = await api.createFromSummary(data.summary);
          break;
        case 'youtube':
          result = await api.createFromYouTube(data.url);
          break;
      }
      
      return { success: true, data: result };
      
    } catch (error) {
      attempt++;
      
      if (attempt >= maxRetries) {
        return { 
          success: false, 
          error: error.message,
          attempts: attempt 
        };
      }
      
      // Wait before retry (exponential backoff)
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
    }
  }
}

2. Rate Limiting

Implement rate limiting to avoid API overuse:

import time
from collections import deque

class RateLimitedMagicSlides:
    def __init__(self, email, access_id, max_requests_per_minute=10):
        self.api = MagicSlidesAPI(email, access_id)
        self.max_requests = max_requests_per_minute
        self.request_times = deque()
    
    def _check_rate_limit(self):
        now = time.time()
        # Remove requests older than 1 minute
        while self.request_times and self.request_times[0] <= now - 60:
            self.request_times.popleft()
        
        if len(self.request_times) >= self.max_requests:
            sleep_time = 60 - (now - self.request_times[0])
            time.sleep(sleep_time)
            self._check_rate_limit()
    
    def create_from_topic(self, topic, extra_info="", slide_count=None):
        self._check_rate_limit()
        self.request_times.append(time.time())
        return self.api.create_from_topic(topic, extra_info, slide_count)

3. Content Optimization

Optimize your content for better presentation generation:

class ContentOptimizer {
  static optimizeTopicInput(topic, context = '') {
    // Ensure topic is descriptive but concise
    const optimizedTopic = topic.length > 100 ? 
      topic.substring(0, 97) + '...' : topic;
    
    // Add helpful context
    const optimizedContext = context || `
      Please create a professional presentation with:
      - Clear, engaging content
      - Visual hierarchy
      - Key takeaways
      - Professional design
    `;
    
    return { topic: optimizedTopic, extraInfo: optimizedContext };
  }
  
  static optimizeSummaryInput(text) {
    // Clean and structure text for better results
    const cleaned = text
      .replace(/\s+/g, ' ')  // Normalize whitespace
      .replace(/[^\w\s.,!?-]/g, '')  // Remove special characters
      .trim();
    
    // Add structure hints if text is unstructured
    if (!cleaned.includes('\n') && cleaned.length > 200) {
      return `Summary: ${cleaned}\n\nPlease structure this into clear sections with main points and supporting details.`;
    }
    
    return cleaned;
  }
  
  static validateYouTubeURL(url) {
    const youtubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)[\w-]+/;
    return youtubeRegex.test(url);
  }
}

Performance Considerations

1. Caching Results

Implement caching to improve performance and reduce API calls:

class CachedMagicSlides {
  constructor(email, accessId, cacheTimeout = 3600000) { // 1 hour default
    this.api = new MagicSlidesAPI(email, accessId);
    this.cache = new Map();
    this.cacheTimeout = cacheTimeout;
  }
  
  _getCacheKey(type, data) {
    return `${type}_${JSON.stringify(data)}`;
  }
  
  _isExpired(timestamp) {
    return Date.now() - timestamp > this.cacheTimeout;
  }
  
  async createFromTopic(topic, extraInfo = '', slideCount = null) {
    const cacheKey = this._getCacheKey('topic', { topic, extraInfo, slideCount });
    const cached = this.cache.get(cacheKey);
    
    if (cached && !this._isExpired(cached.timestamp)) {
      return cached.data;
    }
    
    const result = await this.api.createFromTopic(topic, extraInfo, slideCount);
    this.cache.set(cacheKey, { data: result, timestamp: Date.now() });
    
    return result;
  }
  
  clearCache() {
    this.cache.clear();
  }
  
  getCacheStats() {
    return {
      size: this.cache.size,
      entries: Array.from(this.cache.keys())
    };
  }
}

2. Batch Processing

Process multiple requests efficiently:

import asyncio
import aiohttp

class BatchMagicSlides:
    def __init__(self, email, access_id, max_concurrent=5):
        self.email = email
        self.access_id = access_id
        self.max_concurrent = max_concurrent
        self.semaphore = asyncio.Semaphore(max_concurrent)
    
    async def _make_request(self, session, endpoint, data):
        async with self.semaphore:
            url = f"https://magicslides-tools-api.onrender.com/public/api{endpoint}"
            data.update({"email": self.email, "accessId": self.access_id})
            
            async with session.post(url, json=data) as response:
                return await response.json()
    
    async def batch_create_from_topics(self, topics_data):
        """Process multiple topics concurrently"""
        async with aiohttp.ClientSession() as session:
            tasks = []
            
            for topic_data in topics_data:
                task = self._make_request(
                    session,
                    "/ppt_from_topic",
                    {
                        "topic": topic_data["topic"],
                        "extraInfoSource": topic_data.get("extraInfo", ""),
                        "slideCount": topic_data.get("slideCount")
                    }
                )
                tasks.append(task)
            
            results = await asyncio.gather(*tasks, return_exceptions=True)
            return results
    
    async def mixed_batch_create(self, requests):
        """Process mixed request types concurrently"""
        async with aiohttp.ClientSession() as session:
            tasks = []
            
            for request in requests:
                if request["type"] == "topic":
                    endpoint = "/ppt_from_topic"
                    data = {
                        "topic": request["data"]["topic"],
                        "extraInfoSource": request["data"].get("extraInfo", "")
                    }
                elif request["type"] == "summary":
                    endpoint = "/ppt_from_summery"
                    data = {"msSummaryText": request["data"]["summary"]}
                elif request["type"] == "youtube":
                    endpoint = "/ppt_from_youtube"
                    data = {"youtubeURL": request["data"]["url"]}
                
                if request["data"].get("slideCount"):
                    data["slideCount"] = request["data"]["slideCount"]
                
                task = self._make_request(session, endpoint, data)
                tasks.append(task)
            
            results = await asyncio.gather(*tasks, return_exceptions=True)
            return results

# Usage example
async def main():
    batch_api = BatchMagicSlides("your-email@example.com", "your-access-id")
    
    # Process multiple topics
    topics = [
        {"topic": "AI in Healthcare", "extraInfo": "Focus on diagnostics"},
        {"topic": "Blockchain Applications", "extraInfo": "Business use cases"},
        {"topic": "Sustainable Energy", "extraInfo": "Solar and wind power"}
    ]
    
    results = await batch_api.batch_create_from_topics(topics)
    
    for i, result in enumerate(results):
        if isinstance(result, Exception):
            print(f"Error processing topic {i}: {result}")
        else:
            print(f"Topic {i} presentation URL: {result.get('url')}")

# Run the batch processing
asyncio.run(main())

Security Best Practices

1. Environment Variables

Never hardcode credentials in your source code:

// .env file
MAGICSLIDES_EMAIL=your-email@example.com
MAGICSLIDES_ACCESS_ID=your-access-id

// In your application
require('dotenv').config();

const magicSlides = new MagicSlidesAPI(
  process.env.MAGICSLIDES_EMAIL,
  process.env.MAGICSLIDES_ACCESS_ID
);

2. Input Validation

Always validate user inputs:

class InputValidator {
  static validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }
  
  static validateTopic(topic) {
    if (!topic || typeof topic !== 'string') {
      throw new Error('Topic must be a non-empty string');
    }
    
    if (topic.length < 3) {
      throw new Error('Topic must be at least 3 characters long');
    }
    
    if (topic.length > 200) {
      throw new Error('Topic must be less than 200 characters');
    }
    
    return topic.trim();
  }
  
  static validateYouTubeURL(url) {
    const youtubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)[\w-]+/;
    
    if (!youtubeRegex.test(url)) {
      throw new Error('Invalid YouTube URL format');
    }
    
    return url;
  }
  
  static validateSlideCount(count) {
    if (count !== null && count !== undefined) {
      if (!Number.isInteger(count) || count < 1 || count > 50) {
        throw new Error('Slide count must be an integer between 1 and 50');
      }
    }
    
    return count;
  }
}

Troubleshooting Common Issues

1. API Response Handling

function handleAPIResponse(response) {
  if (!response || typeof response !== 'object') {
    throw new Error('Invalid API response format');
  }
  
  if (response.error) {
    throw new Error(`API Error: ${response.error}`);
  }
  
  if (!response.url) {
    throw new Error('No presentation URL in response');
  }
  
  // Validate URL format
  try {
    new URL(response.url);
  } catch (e) {
    throw new Error('Invalid presentation URL received');
  }
  
  return response;
}

2. Network Error Recovery

import time
import random

def retry_with_backoff(func, max_retries=3, base_delay=1):
    """Retry function with exponential backoff"""
    for attempt in range(max_retries):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries - 1:
                raise e
            
            # Exponential backoff with jitter
            delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
            time.sleep(delay)
            
            print(f"Attempt {attempt + 1} failed, retrying in {delay:.2f}s...")

Conclusion

The MagicSlides API opens up endless possibilities for automating presentation generation across different platforms and use cases. Whether you're building educational tools, content management systems, productivity bots, or social media automation, the API's simplicity and power make it an excellent choice for developers.

Key takeaways:

  • Easy Integration: Simple REST API with clear endpoints
  • Multiple Languages: Examples provided for Node.js, Python, PHP, and cURL
  • Versatile Applications: From Slack bots to CMS plugins
  • Fast Processing: Generate professional presentations in seconds
  • Scalable: Handle batch processing and high-volume operations

Start integrating MagicSlides API into your applications today and transform how your users create and share presentations. The combination of AI-powered generation and simple API integration makes it possible to add powerful presentation capabilities to any application with minimal effort.

For additional support or questions, reach out to the MagicSlides team at support@magicslides.app.

Ready to get started? Sign up for your API access at MagicSlides.app and begin building amazing presentation-powered applications today!