# TypeScript Quickstart

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

## Prerequisites

* Node.js v16 or higher
* npm, yarn, pnpm, or bun package manager
* A ShortGenius API key (get one at [https://shortgenius.com/developers/keys](https://shortgenius.com/developers/keys))

## Installation

Install the ShortGenius TypeScript SDK using your preferred package manager:

{% tabs %}
{% tab title="npm" %}
```bash
npm install shortgenius
```
{% endtab %}

{% tab title="yarn" %}
```bash
yarn add shortgenius
```
{% endtab %}

{% tab title="pnpm" %}
```bash
pnpm add shortgenius
```
{% endtab %}

{% tab title="bun" %}
```bash
bun add shortgenius
```
{% endtab %}
{% endtabs %}

## Quick Start

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

Create a new ShortGenius client instance with your API key:

```typescript
import { ShortGenius } from 'shortgenius'

const client = new ShortGenius({
  bearerAuth: 'YOUR_API_KEY' // or use process.env.SHORTGENIUS_BEARER_AUTH
})
```

{% hint style="info" %}
The SDK will automatically look for the `SHORTGENIUS_BEARER_AUTH` 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:

```typescript
async function checkHealth() {
  const status = await client.status.check()
  console.log('API Status:', status) // { status: "ok" }
}

checkHealth()
```
{% endstep %}

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

Get available music genres for your videos:

```typescript
async function listMusicGenres() {
  const genres = await client.getMusicGenres()
  console.log('Available genres:', genres)

  // Get tracks for a specific genre
  if (genres.length > 0) {
    const tracks = await client.getMusic(genres[0].id)
    console.log(`Tracks in ${genres[0].name}:`, tracks)
  }
}

listMusicGenres()
```
{% endstep %}

{% step %}
**Draft Your First Video**

Create a video draft from a topic:

```typescript
async function draftVideo() {
  const draft = await client.draftVideo({
    topic: 'Benefits of Drinking Water',
    duration: '120',
    locale: 'en-US'
  })

  console.log('Draft created:', draft)
  console.log(`Title: ${draft.title}`)
  console.log(`Scenes: ${draft.scenes.length}`)

  return draft
}

draftVideo()
```
{% endstep %}

{% step %}
**Create the Final Video**

Turn your draft into a rendered video:

```typescript
async function createVideo() {
  // First, get your publishing connections
  const connections = await client.getConnections()

  // Get available voices
  const voices = await client.getVoices({ locale: 'en-US' })

  // Create the draft
  const draft = await client.draftVideo({
    topic: 'Benefits of Drinking Water',
    duration: '120',
    locale: 'en-US'
  })

  // Create the video
  const video = await client.createVideo({
    contentType: 'Custom',
    locale: 'en-US',
    connectionIds: [connections[0].id], // Use your first connection
    title: draft.title,
    caption: draft.caption,
    scenes: draft.scenes,
    voiceId: voices[0].id,
    aspectRatio: '9:16' // 9:16 for vertical video
  })

  console.log('Video created:', video)
  console.log(`Video ID: ${video.id}`)
  console.log(`Status: ${video.publishingState}`)
}

createVideo()
```
{% endstep %}
{% endstepper %}

## Complete Example

Here's a complete example that ties everything together:

```typescript
import { ShortGenius } from 'shortgenius'

const client = new ShortGenius({
  bearerAuth: process.env.SHORTGENIUS_BEARER_AUTH!
})

async function main() {
  // 1. Check API status
  const status = await client.status.check()
  console.log('✅ API is', status.status)

  // 2. Get resources
  const [connections, voices, genres] = await Promise.all([
    client.getConnections(),
    client.getVoices({ locale: 'en-US' }),
    client.getMusicGenres()
  ])

  console.log(`📺 Found ${connections.length} publishing connections`)
  console.log(`🎤 Found ${voices.length} voices`)
  console.log(`🎵 Found ${genres.length} music genres`)

  // 3. Draft a video
  const draft = await client.draftVideo({
    topic: '5 Amazing Space Facts',
    duration: '60',
    locale: 'en-US'
  })

  console.log(`\n📝 Draft created: "${draft.title}"`)
  console.log(`   ${draft.scenes.length} scenes generated`)

  // 4. Get soundtrack
  const tracks = await client.getMusic(genres[0].name)

  // 5. Create the video
  const video = await client.createVideo({
    contentType: 'Custom',
    locale: 'en-US',
    connectionIds: [connections[0].id],
    title: draft.title,
    caption: draft.caption,
    scenes: draft.scenes,
    voiceId: voices[0].id,
    soundtrackId: tracks[0].id,
    aspectRatio: '9:16'
  })

  console.log(`\n🎬 Video created!`)
  console.log(`   ID: ${video.id}`)
  console.log(`   Status: ${video.publishingState}`)

  // 6. Check video status
  const videoDetails = await client.getVideo(video.id)
  console.log(`   Publishing state: ${videoDetails.publishingState}`)
}

main()
```

## Error Handling

The SDK provides typed error responses. Here's how to handle common errors:

```typescript
import { ShortGenius } from 'shortgenius'
import { APIError, APIConnectionError } from 'shortgenius'

const client = new ShortGenius({
  bearerAuth: 'YOUR_API_KEY'
})

async function safeApiCall() {
  const result = await client.getVideo('invalid-id')
  return result
}
```

## Configuration Options

### Custom Timeout

```typescript
const client = new ShortGenius({
  bearerAuth: 'YOUR_API_KEY',
  timeout: 60000 // 60 seconds
})
```

### Custom Base URL

```typescript
const client = new ShortGenius({
  bearerAuth: 'YOUR_API_KEY',
  serverURL: 'https://custom.shortgenius.com/api/v1'
})
```

### Retry Configuration

```typescript
const client = new ShortGenius({
  bearerAuth: 'YOUR_API_KEY',
  retryConfig: {
    strategy: 'backoff',
    backoff: {
      initialInterval: 1000,
      maxInterval: 60000,
      exponent: 1.5,
      maxElapsedTime: 300000
    },
    retryConnectionErrors: true
  }
})
```

## TypeScript Support

The SDK is fully typed, providing excellent IDE support and type safety:

```typescript
import { ShortGenius } from 'shortgenius'
import type { components, operations } from 'shortgenius'

// All request/response types are available
type Video = components.Video
type DraftVideoRequest = operations.DraftVideoRequestBody

// The SDK provides full IntelliSense
const client = new ShortGenius({
  bearerAuth: 'YOUR_API_KEY'
})

// TypeScript will enforce correct parameters
const draft = await client.draftVideo({
  topic: 'Space Facts', // required
  duration: '60', // required
  locale: 'en-US' // optional
  // TypeScript error if you add invalid fields
})
```

## Next Steps

Now that you're up and running with the TypeScript 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/examples).
