Python Examples

Learn how to integrate MagicSlides API into your Python applications using the requests library.

Installation

First, install the requests library:

pip install requests

API Client Setup

import requests
from typing import Dict, Any, Optional

class MagicSlidesAPI:
    def __init__(self, access_id: str, email: str):
        self.base_url = "https://api.magicslides.app/public/api"
        self.access_id = access_id
        self.email = email
        self.headers = {"Content-Type": "application/json"}

    def _make_request(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """Make a POST request to the API with common error handling."""
        url = f"{self.base_url}/{endpoint}"
        
        # Add common parameters
        data.update({
            "accessId": self.access_id,
            "email": self.email
        })
        
        try:
            response = requests.post(url, json=data, headers=self.headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            if response := getattr(e, 'response', None):
                error_data = response.json()
                print(f"API Error: {error_data.get('error')}")
                print(f"Error Code: {error_data.get('code')}")
                if details := error_data.get('details'):
                    print(f"Details: {details}")
            raise

Generate from Topic

def generate_from_topic(self, topic: str, extra_info: Optional[str] = None, slide_count: int = 10) -> Dict[str, Any]:
    """Generate a presentation from a topic."""
    data = {
        "topic": topic,
        "slideCount": slide_count
    }
    
    if extra_info:
        data["extraInfoSource"] = extra_info
    
    return self._make_request("ppt_from_topic", data)

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

try:
    result = api.generate_from_topic(
        topic="Artificial Intelligence in Healthcare",
        extra_info="Focus on recent developments",
        slide_count=12
    )
    print(f"Presentation URL: {result['url']}")
except Exception as e:
    print(f"Failed to generate presentation: {e}")

Generate from Summary

def generate_from_summary(self, summary_text: str, slide_count: int = 10) -> Dict[str, Any]:
    """Generate a presentation from a text summary."""
    data = {
        "msSummaryText": summary_text,
        "slideCount": slide_count
    }
    
    return self._make_request("ppt_from_summery", data)

# Usage example
try:
    result = api.generate_from_summary(
        summary_text="Your detailed summary text here...",
        slide_count=8
    )
    print(f"Presentation URL: {result['url']}")
except Exception as e:
    print(f"Failed to generate presentation: {e}")

Generate from YouTube

def generate_from_youtube(self, video_url: str, slide_count: int = 10) -> Dict[str, Any]:
    """Generate a presentation from a YouTube video."""
    data = {
        "youtubeURL": video_url,
        "slideCount": slide_count
    }
    
    return self._make_request("ppt_from_youtube", data)

# Usage example
try:
    result = api.generate_from_youtube(
        video_url="https://www.youtube.com/watch?v=example",
        slide_count=15
    )
    print(f"Presentation URL: {result['url']}")
except Exception as e:
    print(f"Failed to generate presentation: {e}")

Error Handling

from dataclasses import dataclass
from typing import Optional, Dict, Any

@dataclass
class APIError(Exception):
    message: str
    code: str
    details: Optional[Dict[str, Any]] = None

def handle_api_error(response: requests.Response) -> None:
    """Handle API errors with proper error messages."""
    try:
        error_data = response.json()
        raise APIError(
            message=error_data.get('error', 'Unknown error'),
            code=error_data.get('code', 'UNKNOWN_ERROR'),
            details=error_data.get('details')
        )
    except ValueError:
        raise APIError(
            message=f"HTTP {response.status_code}",
            code='HTTP_ERROR'
        )

# Usage in API client
def _make_request(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
    try:
        response = requests.post(
            f"{self.base_url}/{endpoint}",
            json={**data, "accessId": self.access_id, "email": self.email},
            headers=self.headers
        )
        
        if not response.ok:
            handle_api_error(response)
            
        return response.json()
    except requests.RequestException as e:
        raise APIError(
            message=str(e),
            code='NETWORK_ERROR'
        )

FastAPI Integration

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional

app = FastAPI()
api = MagicSlidesAPI(access_id="your-access-id", email="your-email@example.com")

class TopicRequest(BaseModel):
    topic: str
    extra_info: Optional[str] = None
    slide_count: int = 10

@app.post("/presentations/generate")
async def generate_presentation(request: TopicRequest):
    try:
        result = api.generate_from_topic(
            topic=request.topic,
            extra_info=request.extra_info,
            slide_count=request.slide_count
        )
        return {
            "success": True,
            "url": result["url"],
            "message": result["message"]
        }
    except APIError as e:
        raise HTTPException(
            status_code=400,
            detail={
                "code": e.code,
                "message": e.message,
                "details": e.details
            }
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

Async Support

import aiohttp
import asyncio

async def generate_presentations(topics: list[str]) -> list[dict]:
    """Generate multiple presentations concurrently."""
    async with aiohttp.ClientSession() as session:
        async def generate_one(topic: str) -> dict:
            async with session.post(
                f"{base_url}/ppt_from_topic",
                json={
                    "topic": topic,
                    "accessId": "your-access-id",
                    "email": "your-email@example.com"
                }
            ) as response:
                return await response.json()
        
        tasks = [generate_one(topic) for topic in topics]
        return await asyncio.gather(*tasks)

# Usage example
topics = ["AI in Healthcare", "Machine Learning", "Data Science"]
results = await generate_presentations(topics)

for topic, result in zip(topics, results):
    print(f"Generated presentation for {topic}: {result['url']}")