# Python Examples - MagicSlides API

> Learn how to use the MagicSlides API in your Python applications.

Source: https://www.magicslides.app/docs-api/python
Format: Markdown via content negotiation (`Accept: text/markdown`). Site map for agents: https://www.magicslides.app/llms.txt · API: https://www.magicslides.app/openapi.json

---
# Python Examples

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

**Recommended:** Use the unified `/api/ppt-from-text` endpoint with API key authentication for all new integrations.

## Installation

First, install the requests library:

```bash
pip install requests
```

## API Client Setup

```python
import requests
from typing import Dict, Any, Optional

class MagicSlidesAPI:
    def __init__(self, api_key: str = None, access_id: str = None, email: str = None):
        self.base_url = "https://api.magicslides.app/public/api"
        self.api_key = api_key
        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 authentication - API key takes precedence
        if self.api_key:
            data["apiKey"] = self.api_key
        elif self.access_id and self.email:
            data.update({
                "accessId": self.access_id,
                "email": self.email
            })
        else:
            raise ValueError("Either api_key or both access_id and email must be provided")

        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') or error_data.get('message')}")
                if code := error_data.get('code'):
                    print(f"Error Code: {code}")
                if details := error_data.get('details'):
                    print(f"Details: {details}")
            raise
```

## Unified API - Generate from Topic (Recommended)

```python
def generate_from_topic(self, topic: str, slide_count: int = 10, **kwargs) -> Dict[str, Any]:
    """Generate a presentation from a topic using the unified API."""
    data = {
        "topic": topic,
        "slideCount": slide_count,
        **kwargs
    }

    return self._make_request("ppt-from-text", data)

# Usage example with API key (recommended)
api = MagicSlidesAPI(api_key="ms-api-your-api-key-here")

try:
    result = api.generate_from_topic(
        topic="Introduction to Quantum Computing: Understanding quantum mechanics, qubits, superposition, and quantum algorithms.",
        slide_count=10,
        template="bullet-point1",
        language="en",
        imageForEachSlide=True
    )
    print(f"Presentation URL: {result['url']}")
    print(f"PPT ID: {result['pptId']}")
except Exception as e:
    print(f"Failed to generate presentation: {e}")
```

## Unified API - Generate from Summary

```python
def generate_from_summary(self, summary_text: str, slide_count: int = 10, **kwargs) -> Dict[str, Any]:
    """Generate a presentation from a text summary using the unified API."""
    data = {
        "summary": summary_text,
        "slideCount": slide_count,
        **kwargs
    }

    return self._make_request("ppt-from-text", data)

# Usage example
try:
    result = api.generate_from_summary(
        summary_text="Climate change is one of the most pressing issues of our time...",
        slide_count=10,
        template="bullet-point1",
        language="en"
    )
    print(f"Presentation URL: {result['url']}")
except Exception as e:
    print(f"Failed to generate presentation: {e}")
```

## Unified API - Generate from YouTube

```python
def generate_from_youtube(self, video_url: str, slide_count: int = 10, **kwargs) -> Dict[str, Any]:
    """Generate a presentation from a YouTube video using the unified API."""
    data = {
        "youtubeURL": video_url,
        "slideCount": slide_count,
        **kwargs
    }

    return self._make_request("ppt-from-text", data)

# Usage example
try:
    result = api.generate_from_youtube(
        video_url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
        slide_count=15,
        template="bullet-point1",
        language="en",
        imageForEachSlide=True
    )
    print(f"Presentation URL: {result['url']}")
    print(f"Input Type: {result['inputType']}")
except Exception as e:
    print(f"Failed to generate presentation: {e}")
```

## Error Handling

```python
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

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

app = FastAPI()
api = MagicSlidesAPI(api_key="ms-api-your-api-key-here")

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

```python
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-text",
                json={
                    "apiKey": "ms-api-your-api-key-here",
                    "topic": topic
                }
            ) 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']}")
```
