# MyTechAPI — Media API tutorial

> Generate images, video and audio programmatically, without the
> Playground. Async flow: submit a job, poll for status, download the
> result. Base URL: https://mytechapi.my

## Before you start

You need an API key from https://mytechapi.my/dashboard/kunci. Keys start with
`sk-mytech-` or `mt_`.

**Call this API from your backend, never from the browser.** Your key
must stay on your server in an environment variable such as `.env`. If
you put the key in frontend JavaScript, anyone can steal it and spend
your credits. The API sends no CORS headers, deliberately.

```
Browser (your website)
   │  POST /api/your-own-endpoint
   ▼
Your backend (.env.local: MYTECH_API_KEY=sk-mytech-...)
   │  POST /v1/generations  + Authorization: Bearer <key>
   ▼
MyTechAPI
```

## How it works

1. Submit a job → receive `job_id`, credits are held
2. Poll status until `succeeded` or `failed`
3. Read `output_urls` and download the file

Credits are held on submit. If the job fails, credits are refunded in
full automatically.

## Step 1 — submit

```bash
curl https://mytechapi.my/v1/generations \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "mytech/veo-3.1-text-to-video-quality-1080p",
    "prompt": "a cat leaping across a rooftop",
    "duration": 6
  }'
```

Response (HTTP 202):

```json
{
  "job_id": "1f3c8a2e-...",
  "status": "running",
  "model": "mytech/veo-3.1-text-to-video-quality-1080p",
  "charged_credits": 84787500,
  "poll": "/v1/generations?job_id=1f3c8a2e-..."
}
```

`charged_credits` here is the amount held, not necessarily the final
charge.

## Step 2 — poll

```bash
curl "https://mytechapi.my/v1/generations?job_id=1f3c8a2e-..." \
  -H "Authorization: Bearer ***"
```

Three possible statuses:

```json
{ "status": "running" }
```

```json
{
  "status": "succeeded",
  "output_urls": ["/api/studio/media/1f3c8a2e-..."],
  "charged_credits": 84787500
}
```

```json
{
  "status": "failed",
  "error": "Model tidak dapat memproses permintaan ini.",
  "charged_credits": 0
}
```

Poll every 3–5 seconds. Video usually takes 30–90 seconds; audio and
images are faster. Do not poll more than once a second — you will hit
the rate limit.

## Step 3 — download

`output_urls` contains one or more links, in one of two shapes:

| Shape | How to fetch |
|---|---|
| `/api/studio/media/...` | Prefix with https://mytechapi.my and send the same Authorization header |
| `https://...` | Fetch directly, no header needed |

## Complete code — Python

```python
import os, time, requests

API = "https://mytechapi.my/v1"
KEY = os.environ["MYTECH_API_KEY"]
HEAD = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}

# 1. Submit
res = requests.post(f"{API}/generations", headers=HEAD, json={
    "model": "mytech/veo-3.1-text-to-video-quality-1080p",
    "prompt": "a cat leaping across a rooftop",
    "duration": 6,
})
res.raise_for_status()
job = res.json()
print("job_id:", job["job_id"], "| held:", job["charged_credits"])

# 2. Poll
while True:
    r = requests.get(f"{API}/generations", headers=HEAD,
                     params={"job_id": job["job_id"]}).json()
    if r["status"] in ("succeeded", "failed"):
        break
    time.sleep(5)

# 3. Download
if r["status"] == "succeeded":
    for url in r["output_urls"]:
        full = f"https://mytechapi.my{url}" if url.startswith("/") else url
        headers = HEAD if url.startswith("/") else {}
        data = requests.get(full, headers=headers).content
        name = "output." + ("mp4" if ".mp4" in url else "jpg")
        with open(name, "wb") as f:
            f.write(data)
        print("saved:", name, len(data), "bytes")
else:
    print("failed:", r.get("error"))
```

## Complete code — Node.js

```javascript
const API = "https://mytechapi.my/v1";
const KEY = process.env.MYTECH_API_KEY;
const HEAD = {
  Authorization: `Bearer ${KEY}`,
  "Content-Type": "application/json",
};

// 1. Submit
const job = await fetch(`${API}/generations`, {
  method: "POST",
  headers: HEAD,
  body: JSON.stringify({
    model: "mytech/veo-3.1-text-to-video-quality-1080p",
    prompt: "a cat leaping across a rooftop",
    duration: 6,
  }),
}).then((r) => r.json());

// 2. Poll
let result;
for (let i = 0; i < 120; i++) {
  result = await fetch(`${API}/generations?job_id=${job.job_id}`,
    { headers: HEAD }).then((r) => r.json());
  if (result.status === "succeeded" || result.status === "failed") break;
  await new Promise((r) => setTimeout(r, 5000));
}

// 3. Download
if (result.status === "succeeded") {
  const url = result.output_urls[0];
  const full = url.startsWith("/") ? "https://mytechapi.my" + url : url;
  const res = await fetch(full, url.startsWith("/") ? { headers: HEAD } : {});
  const buf = Buffer.from(await res.arrayBuffer());
  const fs = await import("node:fs/promises");
  await fs.writeFile(url.includes(".mp4") ? "output.mp4" : "output.jpg", buf);
}
```

## Building a website or app (Next.js example)

Backend route — runs on the server, reads the key from `.env.local`:

```typescript
// app/api/generate/route.ts
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const { prompt, duration } = await req.json();

  const submit = await fetch("https://mytechapi.my/v1/generations", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.MYTECH_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "mytech/veo-3.1-text-to-video-quality-1080p",
      prompt,
      duration,
    }),
  });

  if (!submit.ok) {
    return NextResponse.json(await submit.json(), { status: submit.status });
  }
  const job = await submit.json();
  return NextResponse.json({ job_id: job.job_id });
}
```

Frontend — no key here, calls your own backend:

```tsx
// app/generate/page.tsx
"use client";
const res = await fetch("/api/generate", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ prompt, duration: 6 }),
});
const { job_id } = await res.json();
// then poll /api/generate/[jobId] which proxies to MyTechAPI
```

## Other input types

**Image to video** — add `image_urls` (publicly reachable URL):

```json
{
  "model": "mytech/grok-imagine-image-to-video-720p",
  "prompt": "camera pushes in slowly",
  "image_urls": ["https://example.com/photo.jpg"],
  "duration": 6
}
```

**Keyframe (first + last frame)**:

```json
{
  "model": "mytech/kling-4.0-keyframe-to-video-1080p",
  "prompt": "subject walks from @first_frame to @last_frame",
  "first_frame_url": "https://example.com/start.jpg",
  "last_frame_url": "https://example.com/end.jpg",
  "duration": 10
}
```

**Talking avatar (image + audio)** — audio must be MP3 or WAV, 4–300
seconds, max 15 MB:

```json
{
  "model": "mytech/omnihuman-2.0-avatar-video-720p",
  "prompt": "character speaks warmly",
  "image_urls": ["https://example.com/face.jpg"],
  "audio_url": "https://example.com/speech.mp3"
}
```

## Valid durations

| Model family | Seconds |
|---|---|
| Veo 3.1 | 4, 6, 8 |
| Grok Imagine | 6, 10 |
| Runway | 5 (fixed) |
| Kling 4.0 | 3–30 |
| MiniMax H3 | 6, 10 |
| Seedance 2.5 | 4–30 |
| Wan 3.0 | 2–30 |
| Gemini Omni Flash 1.2 | 3–15 |

Out-of-range values are rounded to the nearest valid value and billed at
the actual generated duration. Example: Veo 5s → generated 8s → billed 8s.

## Common errors

| Error | Meaning |
|---|---|
| 402 insufficient_credit | Not enough credits. Top up in the Dashboard. |
| 404 model_not_found | Wrong model ID or model inactive. Check https://mytechapi.my/models |
| 429 rate_limit_exceeded | Too many requests. Reduce poll frequency. |
| status: failed | Generation failed. Credits refunded in full. Try another prompt. |

## See also

- Full API reference: https://mytechapi.my/docs.md
- Models and prices: https://mytechapi.my/models
- Top-level index for agents: https://mytechapi.my/llms.txt
