Tutorial API Media
Jana imej, video dan audio secara program — tanpa menggunakan Playground. Panduan ini merangkumi aliran penuh: hantar tugasan, semak status, dan muat turun hasil.
sk-mytech- atau mt_.⚠ Panggil API ini dari BACKEND anda, bukan dari browser
Kunci API anda mesti kekal di pelayan, dalam pemboleh ubah persekitaran seperti .env — sama seperti panduan ini menggunakan MYTECH_API_KEY. Jika anda letak kunci dalam JavaScript frontend, sesiapa yang buka DevTools boleh curinya dan habiskan kredit anda.
Aliran betul:
Browser (website anda)
↓ panggil endpoint awam anda sendiri
Backend anda (.env.local: MYTECH_API_KEY=sk-mytech-...)
↓ panggil MyTechAPI dengan Authorization header
MyTechAPI /v1/generationsBrowser menyekat panggilan terus dari halaman web ke API ini (tiada header CORS), dan itu memang disengajakan — ia melindungi kunci. Sentiasa salurkan melalui backend anda sendiri.
1. Cara ia berfungsi
Berbeza daripada chat, penjanaan media mengambil masa (saat hingga minit). Jadi API ini tidak segerak — tiga langkah:
2. Langkah 1 — hantar tugasan
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": "seekor kucing melompat di atas bumbung",
"duration": 6
}'Respons (HTTP 202):
{
"job_id": "1f3c8a2e-...",
"status": "running",
"model": "mytech/veo-3.1-text-to-video-quality-1080p",
"charged_credits": 84787500,
"poll": "/v1/generations?job_id=1f3c8a2e-..."
}Simpan job_id. charged_credits di sini ialah jumlah yang ditahan, bukan semestinya caj akhir.
3. Langkah 2 — semak status
curl "https://mytechapi.my/v1/generations?job_id=1f3c..." \
-H "Authorization: Bearer ***"Tiga status yang mungkin:
{
"job_id": "1f3c8a2e-...",
"status": "running",
"model": "mytech/veo-3.1-text-to-video-quality-1080p"
}{
"job_id": "1f3c8a2e-...",
"status": "succeeded",
"model": "mytech/veo-3.1-text-to-video-quality-1080p",
"output_urls": ["/api/studio/media/1f3c8a2e-..."],
"charged_credits": 84787500
}{
"job_id": "1f3c8a2e-...",
"status": "failed",
"model": "mytech/veo-3.1-text-to-video-quality-1080p",
"error": "Model tidak dapat memproses permintaan ini.",
"charged_credits": 0
}4. Langkah 3 — muat turun hasil
output_urls mengandungi satu atau lebih pautan. Dua bentuk mungkin:
| Bentuk | Cara ambil |
|---|---|
| /api/studio/media/… | Tambah awalan https://mytechapi.my dan hantar header Authorization yang sama. |
| https://… | Ambil terus, tiada header diperlukan. |
5. Kod penuh
Sedia untuk salin tampal. Merangkumi hantar, poll dan muat turun.
import os, time, requests
API = f"https://mytechapi.my/v1"
KEY = os.environ["MYTECH_API_KEY"]
HEAD = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
# 1. Hantar tugasan
res = requests.post(f"{API}/generations", headers=HEAD, json={
"model": "mytech/veo-3.1-text-to-video-quality-1080p",
"prompt": "seekor kucing melompat di atas bumbung",
"duration": 6,
})
res.raise_for_status()
job = res.json()
print("job_id:", job["job_id"], "| kredit ditahan:", job["charged_credits"])
# 2. Poll sehingga siap
while True:
r = requests.get(
f"{API}/generations",
headers=HEAD,
params={"job_id": job["job_id"]},
).json()
if r["status"] in ("succeeded", "failed"):
break
print("masih berjalan...")
time.sleep(5)
# 3. Ambil hasil
if r["status"] == "succeeded":
for url in r["output_urls"]:
full = f"https://mytechapi.my{url}" if url.startswith("/") else url
# URL /api/studio/media/... perlukan kunci; URL https://... tidak
headers = HEAD if url.startswith("/") else {}
data = requests.get(full, headers=headers).content
name = "hasil." + ("mp4" if ".mp4" in url else "jpg")
with open(name, "wb") as f:
f.write(data)
print("disimpan:", name, len(data), "bait")
else:
print("gagal:", r.get("error"))
# ---- Contoh lain: imej ke video ----
# tukar json kepada:
# {
# "model": "mytech/grok-imagine-image-to-video-720p",
# "prompt": "kamera bergerak perlahan",
# "image_urls": ["https://example.com/gambar.jpg"],
# "duration": 6,
# }
#
# ---- Contoh lain: avatar bercakap ----
# {
# "model": "mytech/omnihuman-2.0-avatar-video-720p",
# "image_urls": ["https://example.com/wajah.jpg"],
# "audio_url": "https://example.com/suara.mp3",
# }Perlu `pip install requests`. Simpan kunci dalam pemboleh ubah persekitaran MYTECH_API_KEY.
6. Membina website atau app
Ini bahagian yang paling ramai tersilap. Anda tidak boleh panggil MyTechAPI dari JavaScript browser — kunci anda akan kelihatan kepada sesiapa. Letak kunci di pelayan anda dan biar browser bercakap dengan pelayan anda.
Browser (React / Vue / HTML) │ POST /api/jana ← endpoint anda sendiri ▼ Backend anda (Next.js / Express / Laravel / PHP) │ POST /v1/generations ← Authorization: Bearer <kunci> ▼ MyTechAPI
Contoh di bawah guna Next.js API route, tetapi corak yang sama berfungsi dalam Express, Laravel, Django, Flask, atau mana-mana bahasa pelayan.
// app/api/jana/route.ts — ini JALAN DI SERVER, bukan browser
import { NextResponse } from "next/server";
export async function POST(req: Request) {
const { prompt, duration } = await req.json();
// 1. Hantar tugasan ke MyTechAPI
const submit = await fetch("https://mytechapi.my/v1/generations", {
method: "POST",
headers: {
// Kunci dibaca dari .env.local — TIDAK pernah sampai ke browser
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) {
const err = await submit.json();
return NextResponse.json(err, { status: submit.status });
}
const job = await submit.json();
return NextResponse.json({ job_id: job.job_id });
}
// app/api/jana/[jobId]/route.ts — semak status
export async function GET(
_req: Request,
{ params }: { params: { jobId: string } }
) {
const r = await fetch(
`https://mytechapi.my/v1/generations?job_id=${params.jobId}`,
{
headers: {
Authorization: `Bearer ${process.env.MYTECH_API_KEY}`,
},
}
);
const data = await r.json();
return NextResponse.json(data, { status: r.status });
}Fail ini jalan di pelayan. Kunci dari .env.local. Pelayar tidak pernah nampak kunci.
NEXT_PUBLIC_*, VITE_*, atau mana-mana pemboleh ubah yang dihantar ke browser. Awalan itu bermaksud ia memang dihantar ke frontend — sesiapa boleh membacanya.7. Jenis input lain
Imej ke video
Tambah image_urls — URL imej yang boleh dicapai secara awam.
curl https://mytechapi.my/v1/generations \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "mytech/grok-imagine-image-to-video-720p",
"prompt": "kamera bergerak perlahan ke hadapan",
"image_urls": ["https://example.com/gambar-saya.jpg"],
"duration": 6
}'Keyframe (frame mula + akhir)
Dua imej menentukan mula dan akhir. Model mengisi pergerakan di antaranya.
curl https://mytechapi.my/v1/generations \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "mytech/kling-4.0-keyframe-to-video-1080p",
"prompt": "subjek berjalan dari @first_frame ke @last_frame",
"first_frame_url": "https://example.com/mula.jpg",
"last_frame_url": "https://example.com/akhir.jpg",
"duration": 10
}'Avatar bercakap (imej + audio)
Perlu imej potret dan fail audio pertuturan. Audio mesti MP3 atau WAV, 4–300 saat, maksimum 15 MB.
curl https://mytechapi.my/v1/generations \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"model": "mytech/omnihuman-2.0-avatar-video-720p",
"prompt": "watak bercakap dengan mesra",
"image_urls": ["https://example.com/wajah.jpg"],
"audio_url": "https://example.com/suara.mp3"
}'8. Parameter penting
| Keluarga model | Durasi |
|---|---|
| Veo 3.1 | 4 / 6 / 8 |
| Grok Imagine | 6 / 10 |
| Runway | 5 (tetap) |
| 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 |
9. Ralat biasa
402 insufficient_credit
Baki kredit tidak cukup. Top-up di Dashboard.
404 model_not_found
ID model salah atau model tidak aktif. Semak halaman Model.
429 rate_limit_exceeded
Terlalu banyak request. Kurangkan kekerapan poll.
status: failed
Penjanaan gagal. Kredit dipulangkan penuh. Cuba prompt lain.
10. Seterusnya
Guna coding agent AI (Claude Code, Cursor, Codex)? Halakan ia ke versi boleh dibaca mesin:

