# Authentication & Essentials

In this section, we'll discuss how to securely authorize your requests, handle potential errors, and manage credits for ShortGenius services.

## Authentication (Bearer Token)

All ShortGenius endpoints authenticate via the `Authorization: Bearer <token>` header. Two token types are accepted:

* **ShortGenius API keys** (prefixed with `sg-`) — the most common path. Create one from your [API keys dashboard](https://shortgenius.com/developers/keys). Use these for server-to-server integrations and scripts you own.
* **OAuth access tokens** — issued to users who authenticate via the ShortGenius OAuth flow. Use these when acting on behalf of an end user who has granted your application access.

Both token types are sent the same way: `Authorization: Bearer <token>`.

### Using cURL

**How to include your token:**

```
Authorization: Bearer YOUR_API_KEY
```

**Example request:**

```bash
curl --request GET \
  --url "https://api.shortgenius.com/v1/credits" \
  --header "Authorization: Bearer YOUR_API_KEY"
```

### Using SDKs

If you're using one of our official SDKs, authentication is even simpler:

{% tabs %}
{% tab title="TypeScript" %}

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

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

// The SDK automatically includes the bearer token in all requests
const status = await client.status.check()
```

You can also use environment variables:

```typescript
// SDK will automatically use SHORTGENIUS_BEARER_AUTH env variable
const client = new ShortGenius({
  bearerAuth: process.env.SHORTGENIUS_BEARER_AUTH
})
```

{% endtab %}

{% tab title="Python" %}

```python
from shortgenius import Shortgenius

client = Shortgenius(api_key="YOUR_API_KEY")

# The SDK automatically includes the API key in all requests
status = client.status.check()
```

You can also use environment variables:

```python
import os

# SDK will automatically use SHORTGENIUS_API_KEY env variable
client = Shortgenius(
    api_key=os.environ.get("SHORTGENIUS_API_KEY")
)
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Tip**: Always store tokens securely (e.g., environment variables, secret managers). Do not commit them to version control.
{% endhint %}

## Handling Errors

ShortGenius returns standard HTTP status codes together with a JSON body of the shape:

```json
{
  "message": "Human-readable description of what went wrong"
}
```

Common statuses:

| Status Code | Meaning               | Example Message                       |
| ----------- | --------------------- | ------------------------------------- |
| **400**     | Bad Request           | `{"message": "Invalid request"}`      |
| **401**     | Unauthorized          | `{"message": "Unauthorized"}`         |
| **404**     | Not Found             | `{"message": "Not found"}`            |
| **429**     | Too Many Requests     | `{"message": "Too many requests"}`    |
| **500**     | Internal Server Error | `{"message": "Something went wrong"}` |

**Example of a 400 Response:**

```json
{
  "message": "Invalid request"
}
```

### SDK Error Handling

The SDKs provide typed error handling:

{% tabs %}
{% tab title="TypeScript" %}

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

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

const video = await client.getVideo('invalid-id')
```

{% endtab %}

{% tab title="Python" %}

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

client = Shortgenius(api_key="YOUR_API_KEY")

try:
    video = client.videos.retrieve("invalid-id")
except APIError as e:
    print(f"API Error {e.status_code}: {e.message}")

    if e.status_code == 401:
        print("Check your API key")
    elif e.status_code == 404:
        print("Video not found")
    elif e.status_code == 429:
        print("Too many requests, slow down")
```

{% endtab %}
{% endtabs %}

Always inspect the returned JSON for more details on why a request failed.

## Credits & Fair Use

ShortGenius meters usage via a **credit-based system**. Each time you generate a video, image, or audio file, credits are deducted from your account's single `credits` balance. There are no fixed per-minute request quotas published for the public API, but requests are subject to fair-use limits applied at our discretion to protect platform stability; egregious abuse may result in `429 Too Many Requests` responses.

### Checking Your Credit Balance

Use the **GET** `/credits` endpoint to see how many credits remain:

{% tabs %}
{% tab title="TypeScript" %}

```typescript
const usage = await client.getUsage()

console.log(`Credit balance: ${usage.balance.credits}`)
```

{% endtab %}

{% tab title="Python" %}

```python
usage = client.usage.get()

print(f"Credit balance: {usage.balance.credits}")
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl --request GET \
  --url "https://api.shortgenius.com/v1/credits" \
  --header "Authorization: Bearer YOUR_API_KEY"
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Best Practice**: Check your available credits regularly to avoid interruptions, especially before generating large batches of videos or images.
{% endhint %}

***

> **Next Steps**\
> You're now ready to dig into ShortGenius's core functionality. Let's move on to [Video Generation](/api/guides/video-generation.md) to learn how to create short AI-driven clips from scratch.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://shortgenius.gitbook.io/api/essentials.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
