# Python Quickstart

Get up and running with the ShortGenius Python SDK in minutes. This guide will walk you through installation, authentication, and making your first API calls using Python.

## Prerequisites

* Python 3.7 or higher
* pip package manager
* A ShortGenius API key (get one at [https://shortgenius.com/developers/keys](https://shortgenius.com/developers/keys))

## Installation

Install the ShortGenius Python SDK using pip:

```bash
pip install shortgenius
```

For development or to get the latest features:

```bash
pip install --upgrade shortgenius
```

## Quick Start

{% stepper %}
{% step %}
**Initialize the Client**

Create a new ShortGenius client instance with your API key:

```python
from shortgenius import Shortgenius

# Initialize with API key
client = Shortgenius(
    api_key="YOUR_API_KEY"  # or use os.environ.get("SHORTGENIUS_API_KEY")
)
```

{% hint style="info" %}
The SDK will automatically look for the `SHORTGENIUS_API_KEY` environment variable if you don't provide the API key explicitly.
{% endhint %}
{% endstep %}

{% step %}
**Test the Connection**

Verify your setup by checking the API health status:

```python
from shortgenius import Shortgenius

client = Shortgenius(api_key="YOUR_API_KEY")

# Check API health
status = client.health.check()
print(f"API Status: {status.status}")  # Should print: API Status: ok
```
{% endstep %}

{% step %}
**List Available Resources**

Get available voices and check your credits:

```python
# List available voices
voices = client.audio.voices.list_voices(locale="en-US")
print(f"Found {len(voices)} voices")

for voice in voices[:3]:  # Show first 3 voices
    print(f"  - {voice.name} ({voice.source})")
    if voice.tags:
        print(f"    Gender: {voice.tags.gender}, Accent: {voice.tags.accent}")

# Check your credits
credits = client.credits.list()
print(f"Credits: {credits.balance.credits}")
```
{% endstep %}

{% step %}
**Create Images for Your Video**

Generate images that you can use in video creation:

```python
# List available image styles
styles = client.images.list_styles()
print(f"Found {len(styles)} image styles")

# Show first few styles
for style in styles[:3]:
    print(f"  - {style.name}: {style.prompt}")

# Create an image
try:
    image = client.images.create(
        prompt="A serene mountain landscape at sunset",
        aspect_ratio="9:16",
        wait_for_generation=True
    )
    print(f"\nImage created: {image.id}")
    print(f"URL: {image.url}")
except Exception as e:
    print(f"Image creation failed: {e}")
    print("This might be due to insufficient credits")
```
{% endstep %}

{% step %}
**Generate Topics and Create a Video**

Generate video topics and create a video:

```python
# Get necessary resources
connections = client.connections.list()
voices = client.audio.voices.list_voices(locale="en-US")

if not connections:
    print("Please set up a publishing connection first!")
    exit()

# Generate video topics
topics = client.videos.generate_topics(
    parent_topic="space exploration",
    locale="en-US",
    number_of_topics=3
)

print(f"Generated {len(topics)} video topics:")
for i, topic in enumerate(topics[:3], 1):
    print(f"  {i}. {topic}")

# Create a video with a topic
if topics:
    video = client.videos.create(
        topic=topics[0],
        locale="en-US",
        connection_ids=[connections[0].id],
        voice_id=voices[0].id if voices else None,
        aspect_ratio="9:16"
    )

    print(f"\nVideo created!")
    print(f"  ID: {video.id}")
    print(f"  Status: {video.publishing_state}")
```
{% endstep %}
{% endstepper %}

## Complete Example

Here's a complete example that ties everything together:

```python
import os
from shortgenius import Shortgenius
from shortgenius.types import APIError

def main():
    # Initialize client
    client = Shortgenius(
        api_key=os.environ.get("SHORTGENIUS_API_KEY", "YOUR_API_KEY")
    )

    try:
        # 1. Check API status
        status = client.health.check()
        print(f"✅ API is {status.status}")

        # 2. Get resources
        connections = client.connections.list()
        voices = client.audio.voices.list_voices(locale="en-US")
        credits = client.credits.list()

        print(f"📺 Found {len(connections)} publishing connections")
        print(f"🎤 Found {len(voices)} voices")
        print(f"💰 Credits: {credits.balance.credits}")

        if not connections:
            print("❌ Please set up at least one publishing connection")
            return

        # 3. Generate video topics
        print("\n📝 Generating video topics...")
        topics = client.videos.generate_topics(
            parent_topic="space exploration",
            locale="en-US",
            number_of_topics=3
        )

        print(f"   Generated {len(topics)} topics:")
        for i, topic in enumerate(topics, 1):
            print(f"   {i}. {topic}")

        # 4. Create an image for the video
        image = None
        try:
            image = client.images.create(
                prompt="Space exploration scene with stars and planets",
                aspect_ratio="9:16",
                wait_for_generation=True
            )
            print(f"🖼️ Created image: {image.id}")
        except Exception as e:
            print(f"⚠️ Image creation failed: {e}")

        # 5. Create the video
        print("\n🎬 Creating video...")
        if topics:
            video = client.videos.create(
                topic=topics[0],
                locale="en-US",
                connection_ids=[connections[0].id],
                voice_id=voices[0].id if voices else None,
                aspect_ratio="9:16"
            )

            print(f"   Video ID: {video.id}")
            print(f"   Status: {video.publishing_state}")

            # 6. Check video status
            video_details = client.videos.retrieve(video.id)
            print(f"   Publishing state: {video_details.publishing_state}")
        else:
            print("   No topics generated")

    except APIError as e:
        print(f"❌ API Error: {e.message}")
        print(f"   Status code: {e.status_code}")
    except Exception as e:
        print(f"❌ Unexpected error: {e}")

if __name__ == "__main__":
    main()
```

## Error Handling

The SDK provides comprehensive error handling with typed exceptions:

```python
from shortgenius import Shortgenius
from shortgenius.types import (
    APIError,
    APIConnectionError,
    AuthenticationError,
    RateLimitError,
    NotFoundError
)

client = Shortgenius(api_key="YOUR_API_KEY")

try:
    video = client.videos.retrieve("invalid-id")
except AuthenticationError:
    print("Invalid API key")
except NotFoundError:
    print("Video not found")
except RateLimitError as e:
    print(f"Rate limit exceeded. Retry after: {e.retry_after}")
except APIConnectionError:
    print("Network connection error")
except APIError as e:
    print(f"API error {e.status_code}: {e.message}")
```

## Async Support

The SDK also provides an async client for better performance in async applications:

```python
import asyncio
from shortgenius import AsyncShortgenius

async def main():
    # Initialize async client
    async with AsyncShortgenius(api_key="YOUR_API_KEY") as client:
        # All methods are now async
        status = await client.health.check()
        print(f"API Status: {status.status}")

        # Concurrent requests
        voices_task = client.audio.voices.list_voices(locale="en-US")
        credits_task = client.credits.list()

        voices, credits = await asyncio.gather(voices_task, credits_task)
        print(f"Found {len(voices)} voices and {credits.balance.credits} credits")

# Run the async function
asyncio.run(main())
```

## Working with Different Content Types

### Working with Images

```python
# List available image styles
styles = client.images.list_styles()
print(f"Found {len(styles)} styles")

# Create an image with a specific style
cyberpunk_style = next((s for s in styles if "cyberpunk" in s.name.lower()), None)
if cyberpunk_style:
    image = client.images.create(
        prompt="A futuristic robot",
        aspect_ratio="9:16",
        image_style_id=cyberpunk_style.id,
        wait_for_generation=True
    )
    print(f"Styled image created: {image.id}")

# List your created images
response = client.images.list(page=0, limit=10)
for img in response.images:
    print(f"- {img.prompt}: {img.state}")
```

### Working with Audio

```python
# List available voices
voices = client.audio.voices.list_voices(locale="en-US")
for voice in voices:
    print(f"- {voice.name} ({voice.source})")
    if voice.tags:
        print(f"  Gender: {voice.tags.gender}, Accent: {voice.tags.accent}")

# Get details for a specific voice
if voices:
    voice_details = client.audio.voices.retrieve_voice(voices[0].id)
    print(f"Voice details: {voice_details.name}")
    if voice_details.preview_url:
        print(f"Preview: {voice_details.preview_url}")

# Create speech from text
speech = client.audio.create_speech(
    text="Hello, this is a test of the speech generation system.",
    voice_id=voices[0].id if voices else None,
    locale="en-US",
    wait_for_generation=True
)
print(f"Speech created: {speech.id}")
```

### Working with Video Series

```python
# Create a video series
series = client.series.create(
    name="AI Technology Explained",
    description="A series explaining artificial intelligence concepts"
)
print(f"Series created: {series.id}")

# List your series
series_list = client.series.list()
for s in series_list:
    print(f"- {s.name}: {s.description}")
```

## Configuration Options

### Custom Timeout

```python
client = Shortgenius(
    api_key="YOUR_API_KEY",
    timeout=60.0  # 60 seconds
)
```

### Custom Base URL

```python
client = Shortgenius(
    api_key="YOUR_API_KEY",
    base_url="https://custom.shortgenius.com/api/v1"
)
```

### Retry Configuration

```python
client = Shortgenius(
    api_key="YOUR_API_KEY",
    max_retries=3  # Retry failed requests up to 3 times
)
```

### Using Proxies

```python
import httpx

client = Shortgenius(
    api_key="YOUR_API_KEY",
    http_client=httpx.Client(
        proxies="http://proxy.example.com:8080"
    )
)
```

## Working with Responses

All SDK methods return typed response objects:

```python
# Video object attributes
video = client.videos.retrieve(video_id)
print(f"ID: {video.id}")
print(f"Title: {video.title}")
print(f"Caption: {video.caption}")
print(f"Created: {video.created_at}")
print(f"Status: {video.publishing_state}")

# Iterate through paginated results
page = 0
while True:
    response = client.videos.list(page=page, limit=50)

    for video in response.videos:
        print(f"- {video.title} ({video.id})")

    if not response.has_more:
        break

    page += 1
```

## Best Practices

1.  **Environment Variables**: Store your API key in environment variables:

    ```python
    import os
    client = Shortgenius(api_key=os.environ["SHORTGENIUS_API_KEY"])
    ```
2. **Error Handling**: Always wrap API calls in try-except blocks
3. **Rate Limiting**: Implement exponential backoff for rate limit errors
4. **Resource Cleanup**: Use context managers with async client
5.  **Logging**: Enable debug logging for troubleshooting:

    ```python
    import logging
    logging.basicConfig(level=logging.DEBUG)
    ```

## Next Steps

Now that you're up and running with the Python SDK:

* 📖 Check out the [Video Generation Guide](guides/video-generation) for advanced video creation
* 🎨 Learn about [Image Generation](guides/image-generation) for custom visuals
* 🎵 Explore [Audio Generation](guides/audio-generation) for text-to-speech
* 📺 Set up [Publishing Connections](guides/publishing) for automatic distribution
* 📚 View the [Full API Reference](api-reference/editor/create-video)

***

> **Need Help?**\
> Join our [Discord community](https://discord.gg/shortgenius) or check out more examples in our [GitHub repository](https://github.com/shortgenius/python-examples).
