# Magic Hour API Docs > This file is very large and may be truncated. For an index of this content, please refer to https://docs.magichour.ai/llms.txt instead. > Easily generate videos, images, and audio using Magic Hour's API. Follow our documentation to seamlessly integrate AI content creation into your applications. # Get account details Source: https://docs.magichour.ai/api-reference/account/get-account-details get /v1/account Get the current credit balance and subscription details of the account that owns the API key. # AI Music Generator Source: https://docs.magichour.ai/api-reference/audio-projects/ai-music-generator post /v1/ai-music-generator Generate music from a description, with optional custom lyrics or instrumental-only output. Costs 1 credits per requested second. Returns a project ID; poll GET /v1/audio-projects/{id} for status and downloads. # AI Voice Cloner API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/audio-projects/ai-voice-cloner post /v1/ai-voice-cloner Clone a voice from an audio sample and generate speech. * Each character costs 0.1 credits. * The cost is rounded up to the nearest whole number # AI Voice Generator API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/audio-projects/ai-voice-generator post /v1/ai-voice-generator Generate speech from text. Each character costs 0.1 credits. The cost is rounded up to the nearest whole number. # Delete Audio API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/audio-projects/delete-audio delete /v1/audio-projects/{id} Permanently delete the rendered audio file(s). This action is not reversible, please be sure before deleting. # Estimate audio credits Source: https://docs.magichour.ai/api-reference/audio-projects/estimate-audio-credits get /v1/estimate/audio Get the credits an audio create request charges. Pass `tool`, then the field below that the tool's create request uses. Does not create a project or spend credits. It prices the fields passed here. It does not check your plan, your balance or the rest of the create request. # Get Audio Details API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/audio-projects/get-audio-details get /v1/audio-projects/{id} Check the progress of a audio project. The `downloads` field is populated after a successful render. **Statuses** - `queued` — waiting to start - `rendering` — in progress - `complete` — ready; see `downloads` - `error` — a failure occurred (see `error`) - `canceled` — user canceled - `draft` — not used # List voices Source: https://docs.magichour.ai/api-reference/audio-projects/list-voices get /v1/voices List the voices available for text-to-speech. Use a voice's `id` as `style.voice_name` in the AI Voice Generator API. To fetch the next page, pass the response's next_cursor as cursor. # Face Detection API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/files/face-detection post /v1/face-detection Detect faces in an image or video. Use this API to get the list of faces detected in the image or video to use in the [face swap photo](https://docs.magichour.ai/api-reference/image-projects/face-swap-photo) or [face swap video](https://docs.magichour.ai/api-reference/video-projects/face-swap-video) API calls for multi-face swaps. Note: Face detection is free to use for the near future. Pricing may change in the future. # Generate Asset Upload Urls API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/files/generate-asset-upload-urls post /v1/files/upload-urls Generates a list of pre-signed upload URLs for the assets required. This API is only necessary if you want to upload to Magic Hour's storage. Refer to the [Input Files Guide](https://docs.magichour.ai/integration/inputs-and-outputs) for more details. The response array will match the order of items in the request body. **Valid file extensions per asset type**: - video: mp4, m4v, mov, webm - audio: mp3, wav, aac, flac, webm, weba, m4a, opus, ogg, oga, aiff, amr - image: png, jpg, jpeg, jpe, jfif, heic, heif, webp, avif, jp2, tiff, tif, bmp - gif: gif, webp, webm > Note: `gif` is only supported for face swap API `video_file_path` field. Once you receive an upload URL, send a `PUT` request to upload the file directly. Example: ``` curl -X PUT --data-binary '@/path/to/file/video.mp4' \ "https://videos.magichour.ai/api-assets/id/video.mp4?" ``` # Get Face Detection Details API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/files/get-face-detection-details get /v1/face-detection/{id} Get the details of a face detection task. Use this API to get the list of faces detected in the image or video to use in the [face swap photo](https://docs.magichour.ai/api-reference/image-projects/face-swap-photo) or [face swap video](https://docs.magichour.ai/api-reference/video-projects/face-swap-video) API calls for multi-face swaps. When `status` is `error`, the `error` field explains why (for example `nsfw` when the content-safety filter blocked the file). It is `null` otherwise. # List saved items Source: https://docs.magichour.ai/api-reference/files/list-saved-items get /v1/saved-items Returns active saved items owned by the authenticated account, newest first. Each item includes every saved asset with a durable file_path for reuse in compatible generation APIs and a temporary signed URL for previewing or downloading. Filter by type to find characters, references, voices, moodboards, or brand kits. To fetch the next page, pass the response's next_cursor as cursor. # AI Clothes Changer API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-clothes-changer post /v1/ai-clothes-changer Change outfits in photos in seconds with just a photo reference. Each photo costs 25 credits. # AI Face Editor API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-face-editor post /v1/ai-face-editor Edit facial features of an image using AI. Each edit costs 1 frame. The height/width of the output image depends on your subscription. Please refer to our [pricing](https://magichour.ai/pricing) page for more details # AI GIF Generator API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-gif-generator post /v1/ai-gif-generator Create an AI GIF. Each GIF costs 50 credits. # AI Headshot Generator API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-headshot-generator post /v1/ai-headshot-generator Create a 4:5 AI headshot. Each headshot costs 50 credits. # AI Image Editor API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-image-editor post /v1/ai-image-editor Edit images with AI. # AI Image Generator API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-image-generator post /v1/ai-image-generator Create an AI image with advanced model selection and quality controls. # AI Image Upscaler API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-image-upscaler post /v1/ai-image-upscaler Upscale your image using AI. Each 2x upscale costs 50 credits for balanced/creative modes, and 25 credits for preserve. 4x upscale costs 200 and 100 credits respectively. # AI Meme Generator API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-meme-generator post /v1/ai-meme-generator Create an AI generated meme. Each meme costs 10 credits. # AI QR Code Generator API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/ai-qr-code-generator post /v1/ai-qr-code-generator Create an AI QR code. Each QR code costs 0 credits. # Body Swap Source: https://docs.magichour.ai/api-reference/image-projects/body-swap post /v1/body-swap Swap a person into a scene image using Nano Banana 2 Lite (640px/1k) or Nano Banana 2.1 (2k/4k). Credits depend on `resolution` (from 50 credits at 640px upward). # Delete Image API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/delete-image delete /v1/image-projects/{id} Permanently delete the rendered image(s). This action is not reversible, please be sure before deleting. # Estimate image credits Source: https://docs.magichour.ai/api-reference/image-projects/estimate-image-credits get /v1/estimate/image Get the credits an image create request charges. Pass `tool`, then the fields below that the tool's create request uses, with the same values. Does not create a project or spend credits. It prices the fields passed here. It does not check your plan, your balance or the rest of the create request. # Face Swap Photo API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/face-swap-photo post /v1/face-swap-photo Create a face swap photo. Each photo costs 10 credits. The height/width of the output image depends on your subscription. Please refer to our [pricing](https://magichour.ai/pricing) page for more details # Get Image Details API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/get-image-details get /v1/image-projects/{id} Check the progress of a image project. The `downloads` field is populated after a successful render. **Statuses** - `queued` — waiting to start - `rendering` — in progress - `complete` — ready; see `downloads` - `error` — a failure occurred (see `error`) - `canceled` — user canceled - `draft` — not used # Head Swap API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/head-swap post /v1/head-swap Swap a head onto a body image. Each image costs 10 credits. Output resolution depends on your subscription; you may set `max_resolution` lower than your plan maximum if desired. # Image Background Remover API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/image-background-remover post /v1/image-background-remover Remove background from image. Each image costs 5 credits. # Photo Colorizer API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/image-projects/photo-colorizer post /v1/photo-colorizer Colorize image. Each image costs 10 credits. # Models and Credit Costs Source: https://docs.magichour.ai/api-reference/models Every model available through the API, what it supports, and what it costs in credits. Magic Hour exposes multiple models per endpoint. Pass the one you want in the `model` field, or omit it to get `default`, which tracks our current recommendation and changes over time. Credits are charged per generation. Video cost scales with duration, image cost with resolution and image count. Failed generations are never charged. ## Video models Available on [text to video](/api-reference/video-projects/text-to-video) and [image to video](/api-reference/video-projects/image-to-video). ### Choose your first model Start with a model available on the free plan. Free-plan access still uses credits. **Available on free and paid plans** * **LTX 2.5 (`ltx-2.5`)** — our recommended starting point, especially for fast generations. * **MiniMax H3 (`minimax-h3`)** — a high-quality alternative. * **Wan 2.2 (`wan-2.2`)** — an option for action and camera movement without generated audio. On the Free plan, set `resolution` to `480p` when you specify any of these model IDs. If you leave `resolution` out, the request can default to a paid resolution. **Requires a paid plan** * **Kling 3.0 (`kling-3.0`)** — our recommendation for strong quality and value. * **Seedance 2.5 (`seedance-2.5`)** — choose this for state-of-the-art quality. The other models in the video reference require a paid plan. Pass the model ID in `model` to select it explicitly. See the endpoint reference for supported durations and resolutions, and the credit-cost table below to compare costs. ### Video model reference | Model | Best for | Resolutions | Durations (seconds) | Audio | | :- | :- | :- | :- | :- | | `ltx-2.5` | Fast output for general scenes and clips up to 60 seconds | 480p, 720p, 1080p | Any integer from 1 to 60 | Yes, no extra credits | | `minimax-h3` | Native-audio video with flexible duration | 480p, 720p, 1080p | Any integer from 1 to 30 | Yes, no extra credits | | `wan-2.2` | Strong physics, camera moves, and motion | 480p, 720p, 1080p | 3, 4, 5, 6, 7, 8, 9, 10, 15 | No | | `gemini-omni-1.2` | Precise short clips, first and last frames, and high resolution | 360p, 720p, 1080p, 4k | Any integer from 3 to 15 | Yes, no extra credits | | `wan-3.0` | Native-audio video, long clips, and end-frame control | 480p, 720p, 1080p | Any integer from 2 to 30 | Yes, no extra credits | | `kling-2.6` | Great for action, motion blur, and camera moves | 720p, 1080p | 5, 10 | No | | `kling-4.0` | Cinematic video with image/video references and optional audio | 720p, 1080p | Any integer from 3 to 30 | Yes, no extra credits | | `kling-3.0` | Best overall quality for cinematic storytelling | 720p, 1080p, 4k | 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 | Yes, costs extra | | `veo3.1-lite` | Veo quality at a more accessible cost | 720p, 1080p | 4, 6, 8, 16, 24, 32, 40, 48, 56 | Yes, costs extra | | `veo3.1` | Google's model. Highest realism and detail | 720p, 1080p | 4, 6, 8, 16, 24, 32, 40, 48, 56 | Yes, costs extra | | `seedance-1.5` | Smooth, consistent motion with precision | 480p, 720p, 1080p | 4, 5, 6, 7, 8, 9, 10, 11, 12 | Yes, costs extra | | `seedance-2.0-mini` | Fast, consistent video with strong motion quality | 480p, 720p | 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 | Yes, no extra credits | | `seedance-2.0-fast` | Fast reference-led clips with consistent motion and audio | 480p, 720p | 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 | Yes, no extra credits | | `seedance-2.0` | Top quality with reference-to-video control | 480p, 720p, 1080p, 4k | 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 | Yes, no extra credits | | `seedance-2.5` | Highest quality with superior realism, detail, and motion | 480p, 720p, 1080p, 4k | 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 | Yes, no extra credits | > [!NOTE] > > With `model="default"`, Text-to-Video and Image-to-Video use `ltx-2.5` on the Free plan. Paid > requests at `480p` use `seedance-1.5`. At other resolutions, paid requests longer than 15 seconds > use `ltx-2.5` and requests up to 15 seconds use `kling-3.0`. The selected model's resolution and > duration limits still apply. Free typically requests `480p`. Paid plans (Creator, Pro, Business) > can request the higher resolutions a model supports, at that resolution's credit cost. `wan-3.0` > requires a paid plan at every resolution. `gemini-omni-1.2` also requires a paid plan and supports > an end frame on Image-to-Video clips up to 10 seconds. `kling-4.0` requires a paid plan and supports > up to 10 API references total, including at most one video. The API rejects `kling-2.5-audio` > because its replacement, Kling 2.6, does not support native audio. The deprecated `veo3.1-audio` > value maps to `veo3.1` with `audio: true`. ### Video credit costs Credits per second of output. For text-to-video and image-to-video, multiply by `end_seconds` to estimate a job. For endpoints that trim an input, the clip duration is `end_seconds - start_seconds`. See a [five-second image-to-video cost example](/integration/evaluating-media-apis#example-budget-a-five-second-product-clip) for how credits translate under different funding arrangements. For Kling 3.0, compare the [Creator, Pro and Business annual subscription example](/billing/subscription-pricing#kling-3-0-annual-pricing-example), including the full upfront payment and effective cost at each resolution and audio setting. | Model | 360p | 480p | 720p | 1080p | 4k | With audio | | :- | -: | -: | -: | -: | -: | :- | | `ltx-2.5` | — | 24 | 48 | 72 | — | Included | | `minimax-h3` | — | 24 | 48 | 72 | — | Included | | `wan-2.2` | — | 24 | 48 | 72 | — | Not supported | | `gemini-omni-1.2` | 30 | — | 72 | 102 | 192 | Included | | `wan-3.0` | — | 48 | 96 | 180 | — | Included | | `kling-2.6` | — | — | 36 | 48 | — | Not supported | | `kling-4.0` | — | — | 80 | 120 | — | Included | | `kling-3.0` | — | — | 60 | 72 | 264 | +24 at 720p; +36 at 1080p; +24 at 4k | | `veo3.1-lite` | — | — | 48 | 72 | — | +24 | | `veo3.1` | — | — | 96 | 120 | — | +24 | | `seedance-1.5` | — | 30 | 60 | 90 | — | 2× the base rate | | `seedance-2.0-mini` | — | 48 | 120 | — | — | Included | | `seedance-2.0-fast` | — | 84 | 180 | — | — | Included | | `seedance-2.0` | — | 96 | 216 | 528 | 1104 | Included | | `seedance-2.5` | — | 144 | 288 | 720 | 1080 | Included | The video formula is `duration × output fps × resolution multiplier`. Because output fps varies by model, two models at the same resolution can cost different amounts per second. ### Video-reference pricing Supplying a video in `references` can change the rate. These are total credits per output second, not additions to the base price. A listed video-reference rate takes precedence over the audio rate. For other supported combinations, use the model's base or audio rate. | Model | 360p | 480p | 720p | 1080p | 4k | | :- | -: | -: | -: | -: | -: | | `gemini-omni-1.2` | 54 | - | 96 | 126 | 216 | | `kling-4.0` | - | - | 96 | 144 | - | | `kling-3.0` | - | - | 108 | 144 | - | | `seedance-2.0-mini` | - | 72 | 144 | - | - | | `seedance-2.0-fast` | - | 96 | 216 | - | - | | `seedance-2.0` | - | 96 | 216 | 672 | 1320 | | `seedance-2.5` | - | \~165 | \~350 | 864 | \~1327 | A dash means no separate video-reference rate is listed. Check the endpoint reference for supported input types and model/resolution combinations. ### Legacy model values The endpoints still accept `ltx-2`, `ltx-2.3`, `kling-2.5`, `kling-1.6`, `seedance` for backwards compatibility, but these are no longer recommended and are absent from the tables above. New integrations should use a documented model. Existing Text-to-Video and Image-to-Video requests using `gemini-omni-1.1` run on `gemini-omni-1.2` at the 1.2 rates. Text-to-Video and Image-to-Video still accept `sora-2` for compatibility. Those requests run `minimax-h3` and use MiniMax H3’s current limits and credit rates. Use `minimax-h3` for new requests. [AI video editor](/api-reference/video-projects/ai-video-editor) has its own roster: `gemini-omni-1.2`, `wan-3.0`, `ltx-2.5`, and `kling-4.0`. The default is `ltx-2.5` on the free tier and `gemini-omni-1.2` on paid tiers. The other models require a paid plan. On this endpoint, `ltx-2.3` maps to `ltx-2.5`, and `gemini-omni` and `gemini-omni-1.1` map to `gemini-omni-1.2`. ## Image models Available on [AI image generator](/api-reference/image-projects/ai-image-generator) and [AI image editor](/api-reference/image-projects/ai-image-editor). | Model | Generate | Edit | Resolutions | From | Tiers | | :- | :- | :- | :- | -: | :- | | `flux-schnell` | Yes | — | 640px, 1k, 2k | 5 credits | free, creator, pro, business | | `flux-2-klein` | Yes | Yes | 640px, 1k, 2k | 5 credits | free, creator, pro, business | | `flux-3-klein` | Yes | Yes | 640px, 1k, 2k | 5 credits | free, creator, pro, business | | `z-image-turbo` | Yes | — | 640px, 1k, 2k | 5 credits | free, creator, pro, business | | `seedream-v4` | Yes | Yes | 640px, 1k, 2k, 4k | 40 credits | creator, pro, business | | `seedream-v5-flash` | Yes | Yes | 640px, 1k, 2k | 30 credits | creator, pro, business | | `seedream-v5-pro` | Yes | Yes | 640px, 1k, 2k | 75 credits | creator, pro, business | | `nano-banana` | Yes | Yes | 640px, 1k | 50 credits | creator, pro, business | | `nano-banana-2-lite` | Yes | Yes | 640px, 1k | 50 credits | creator, pro, business | | `nano-banana-2.1` | Yes | Yes | 640px, 1k, 2k, 4k | 50 credits | creator, pro, business | | `nano-banana-pro` | Yes | Yes | 1k, 2k, 4k | 150 credits | creator, pro, business | | `gpt-image-2` | Yes | Yes | 640px, 1k, 2k, 4k | 50 credits | creator, pro, business | | `gpt-image-2.5-flare` | Yes | Yes | 640px, 1k, 2k, 4k | 100 credits | creator, pro, business | | `krea-2` | Yes | Yes | 640px, 1k | 10 credits | free, creator, pro, business | | `qwen-edit` | — | Yes | 640px, 1k, 2k | 10 credits | free, creator, pro, business | | `qwen-image-2.1` | Yes | Yes | 640px, 1k, 2k | 10 credits | free, creator, pro, business | | `seedream-v4.5` | Yes | Yes | 640px, 1k, 2k, 4k | 50 credits | creator, pro, business | "From" is the cost of a single image at the model's lowest resolution. Cost depends on the model, resolution, and image count; do not assume every batch costs the single-image rate multiplied by the count. For example, `nano-banana-2.1` costs 50 credits for one image at `640px` or `1k`, and 150 credits total for a grid of 4, 9, or 16 images. Free-plan image models are available at `640px`. Larger resolutions require a paid plan even if the model is available on the free plan. Set `model` to `nano-banana-2.1` explicitly to use the 2.1 rates above. If your integration sends `nano-banana-2`, check the current model and credit details for the [generator](/api-reference/image-projects/ai-image-generator#body-model) or [editor](/api-reference/image-projects/ai-image-editor#body-model) before estimating cost. The generator reference also lists the available resolutions and credits for Seedream 4.5. | Model | Allowed image counts (generator) | Max additional input images (editor) | | :- | :- | :- | | `flux-schnell` | 1, 2, 3, 4 | — | | `flux-2-klein` | 1 | 5 | | `flux-3-klein` | 1, 2, 3, 4 | 1 | | `z-image-turbo` | 1, 2, 3, 4 | — | | `seedream-v4` | 1, 2, 3, 4 | 9 | | `seedream-v5-flash` | 1, 2, 3, 4 | 9 | | `seedream-v5-pro` | 1, 2, 3, 4 | 9 | | `nano-banana` | 1, 2, 3, 4 | 9 | | `nano-banana-2-lite` | 1, 2, 3, 4 | 9 | | `nano-banana-2.1` | 1, 4, 9, 16 | 9 | | `nano-banana-pro` | 1, 4, 9, 16 | 9 | | `gpt-image-2` | 1, 2, 3, 4 | 9 | | `gpt-image-2.5-flare` | 1, 2, 3, 4 | 9 | | `krea-2` | 1 | 1 | | `qwen-edit` | — | 2 | | `qwen-image-2.1` | 1, 2, 3, 4 | 2 | | `seedream-v4.5` | 1, 2, 3, 4 | 9 | ## Reference costs These endpoints use tool-specific pricing. Some rates vary by resolution or output settings. | Endpoint | Credits | | :- | :- | | [AI Clothes Changer](/api-reference/image-projects/ai-clothes-changer) | 25 per image | | [AI Face Editor](/api-reference/image-projects/ai-face-editor) | 1 per edit | | [AI GIF Generator](/api-reference/image-projects/ai-gif-generator) | 50 per GIF | | [AI Headshot Generator](/api-reference/image-projects/ai-headshot-generator) | 50 per headshot | | [AI Meme Generator](/api-reference/image-projects/ai-meme-generator) | 10 per meme | | [AI QR Code Generator](/api-reference/image-projects/ai-qr-code-generator) | Free | | [Body Swap](/api-reference/image-projects/body-swap) | 50+ per image, based on resolution | | [Face Swap Photo](/api-reference/image-projects/face-swap-photo) | 10 per image | | [Head Swap](/api-reference/image-projects/head-swap) | 10 per image | | [Image Background Remover](/api-reference/image-projects/image-background-remover) | 5 per image | | [Photo Colorizer](/api-reference/image-projects/photo-colorizer) | 10 per image | | [AI Voice Generator](/api-reference/audio-projects/ai-voice-generator) | 0.1 per character, rounded up | | [AI Voice Cloner](/api-reference/audio-projects/ai-voice-cloner) | 0.1 per generated character, rounded up | ### AI Image Upscaler Cost depends on `style.mode` and `scale_factor`. | Mode and scale | Credits | | :- | :- | | `preserve`, 2x | 25 per image | | `balanced` or `creative`, 2x | 50 per image | | `preserve`, 4x | 100 per image | | `balanced` or `creative`, 4x | 200 per image | ## Duration-based endpoints These charge by output length rather than per generation. | Endpoint | Credits | | :- | :- | | [AI Music Generator](/api-reference/audio-projects/ai-music-generator) | 1 credit per requested second (15–300 seconds) | | [Animation](/api-reference/video-projects/animation) | 24 credits/second at 24fps | | [Audio to Video](/api-reference/video-projects/audio-to-video) | 24 credits/second at 480p, 48 at 720p, 72 at 1080p | | [Auto Subtitle Generator](/api-reference/video-projects/auto-subtitle-generator) | \~4.8 credits/second at 24fps | | [Character Replace](/api-reference/video-projects/character-replace) | [Model-specific rates below](#character-replace) | | [Face Swap Video](/api-reference/video-projects/face-swap-video) | 24 credits/second at 24fps | | [Lip Sync](/api-reference/video-projects/lip-sync) | 1 credit/frame, doubled on `pro` | | [AI Talking Photo](/api-reference/video-projects/ai-talking-photo) | 24 credits/second prompted, 48 realistic at 24 fps | | [Video to Video](/api-reference/video-projects/video-to-video) | 48 credits/second at 24fps | > [!NOTE] > > Video jobs return an estimate in `credits_charged` on the create response. The final amount is > corrected once the render finishes and the true frame rate is known. Read `credits_charged` from > the get-details response for the actual charge. ### Character Replace Credits per output second depend on `model` and `resolution`. | Model | 480p | 720p | 1080p | | :- | -: | -: | -: | | `wan-animate` | 48 | 96 | - | | `kling-3.0` | - | 60 | 72 | | `kling-4.0` | - | 96 | 144 | | `minimax-h3` | 48 | 96 | 144 | A dash means that resolution is unsupported for that model in Character Replace. See the [Character Replace guide](/tools/video/character-replace#modes-and-resolution) for mode-specific duration limits and subject selection. ## Estimating before you build * **Estimate one request.** Use the read-only [video estimate](/api-reference/video-projects/estimate-video-credits), [image estimate](/api-reference/image-projects/estimate-image-credits), or [audio estimate](/api-reference/audio-projects/estimate-audio-credits) for a supported tool. Pass the settings you intend to submit. The quote covers the credit cost of those settings. Check the model and resolution limits for your plan before creating a project. * **Credits to dollars** — [subscription and credit-pack prices](/billing/overview) set what each credit costs. * **Cost calculator** — [model your monthly spend](https://magichour.ai/api?ref=docs-models#api-cost-calculator) across endpoints and volumes. * **Mock server** — [develop against sample responses](/integration/development-and-testing#mock-server-recommended-for-development) without spending credits. * **Current tier and balance.** Call [`GET /v1/account`](/api-reference/account/get-account-details) to see the active subscription tier and available credits for the API key's account. # API Reference Source: https://docs.magichour.ai/api-reference/overview Find Magic Hour API endpoints for media creation, project status, uploads, and credit estimates. Magic Hour APIs create and manage video, image, and audio projects. Most creation endpoints return a project ID immediately; use the matching details endpoint or a webhook to track completion. > [card] [Quick start](/get-started/quick-start) > > Create a key and complete your first generation. > [card] [Models and credit costs](/api-reference/models) > > Compare every model's resolutions, durations, and cost. > [card] [Processing times](/api-reference/processing-times) > > See observed median end-to-end times. > [card] [Integration lifecycle](/integration/overview) > > Learn how to submit, monitor, and download projects. ## Start with an outcome Choose the workflow you want to build. Each guide explains the required inputs, pricing, expected processing time, and links to the complete endpoint specification. > [card] [Generate an image](/tools/image/image-generator) > > Create images from text prompts. > [card] [Edit an image](/tools/image/image-editor) > > Transform one or more images with a text instruction. > [card] [Animate an image](/tools/video/image-to-video) > > Turn a still image into a video. > [card] [Make a photo talk](/tools/video/talking-photo) > > Animate a portrait with an audio file. > [card] [Swap a face in video](/tools/video/face-swap-video) > > Replace one or more faces in a video. > [card] [Use an AI agent](/integration/model-context-protocol) > > Connect Claude, ChatGPT, Claude Code, or Codex through MCP. For reference-led workflows, see [named media references](/tools/video/text-to-video#reference-media) and [saved library assets](/integration/inputs-and-outputs#reuse-saved-assets). > [!TIP] > > New to the API? Start with image generation. It is the fastest, lowest-cost way to verify your API > key, request handling, job completion, and downloads end to end. ## Estimate credits Estimate a request before submitting a job. Each endpoint returns `estimated_credits` without spending credits. Check [model availability](/api-reference/models) and your [credit balance](/api-reference/account/get-account-details) before generating. * [`GET /v1/estimate/image`](/api-reference/image-projects/estimate-image-credits) * [`GET /v1/estimate/video`](/api-reference/video-projects/estimate-video-credits) * [`GET /v1/estimate/audio`](/api-reference/audio-projects/estimate-audio-credits) [Copy a cURL request](/billing/overview#run-a-credit-estimate) for image, video, or speech. ## Account * [`GET /v1/account`](/api-reference/account/get-account-details) — Get the current credit balance and subscription details for the account that owns the API key ## Files * [`GET /v1/saved-items`](/api-reference/files/list-saved-items) - List reusable saved assets * [`POST /v1/files/upload-urls`](/api-reference/files/generate-asset-upload-urls) — Generate asset upload URLs * [`POST /v1/face-detection`](/api-reference/files/face-detection) — Detect faces in an asset * [`GET /v1/face-detection/:id`](/api-reference/files/get-face-detection-details) — Get face detection details ## Video projects ### Manage projects * [`GET /v1/video-projects/:id`](/api-reference/video-projects/get-video-details) — Get video details * [`DELETE /v1/video-projects/:id`](/api-reference/video-projects/delete-video) — Delete a video ### Create projects * [`POST /v1/ai-talking-photo`](/api-reference/video-projects/ai-talking-photo) — AI Talking Photo * [`POST /v1/ai-ugc-ad`](/api-reference/video-projects/ai-ugc-ad-generator) - AI UGC Ad Generator * [`POST /v1/ai-video-upscaler`](/api-reference/video-projects/ai-video-upscaler) - AI Video Upscaler * [`POST /v1/ai-video-editor`](/api-reference/video-projects/ai-video-editor) — AI Video Editor * [`POST /v1/ai-video-translator`](/api-reference/video-projects/ai-video-translator) — AI Video Translator * [`POST /v1/animation`](/api-reference/video-projects/animation) — Animation * [`POST /v1/audio-to-video`](/api-reference/video-projects/audio-to-video) — Audio to Video * [`POST /v1/auto-subtitle-generator`](/api-reference/video-projects/auto-subtitle-generator) — Auto Subtitle Generator * [`POST /v1/character-replace`](/api-reference/video-projects/character-replace) — Character Replace * [`POST /v1/face-swap`](/api-reference/video-projects/face-swap-video) — Face Swap Video * [`POST /v1/image-to-video`](/api-reference/video-projects/image-to-video) — Image to Video * [`POST /v1/lip-sync`](/api-reference/video-projects/lip-sync) — Lip Sync * [`POST /v1/text-to-video`](/api-reference/video-projects/text-to-video) — Text to Video * [`POST /v1/video-to-video`](/api-reference/video-projects/video-to-video) — Video to Video ## Image projects ### Manage projects * [`GET /v1/image-projects/:id`](/api-reference/image-projects/get-image-details) — Get image details * [`DELETE /v1/image-projects/:id`](/api-reference/image-projects/delete-image) — Delete an image ### Create projects * [`POST /v1/ai-clothes-changer`](/api-reference/image-projects/ai-clothes-changer) — AI Clothes Changer * [`POST /v1/ai-face-editor`](/api-reference/image-projects/ai-face-editor) — AI Face Editor * [`POST /v1/ai-gif-generator`](/api-reference/image-projects/ai-gif-generator) — AI GIF Generator * [`POST /v1/ai-headshot-generator`](/api-reference/image-projects/ai-headshot-generator) — AI Headshot Generator * [`POST /v1/ai-image-editor`](/api-reference/image-projects/ai-image-editor) — AI Image Editor * [`POST /v1/ai-image-generator`](/api-reference/image-projects/ai-image-generator) — AI Image Generator * [`POST /v1/ai-image-upscaler`](/api-reference/image-projects/ai-image-upscaler) — AI Image Upscaler * [`POST /v1/ai-meme-generator`](/api-reference/image-projects/ai-meme-generator) — AI Meme Generator * [`POST /v1/ai-qr-code-generator`](/api-reference/image-projects/ai-qr-code-generator) — AI QR Code Generator * [`POST /v1/body-swap`](/api-reference/image-projects/body-swap) — Body Swap * [`POST /v1/face-swap-photo`](/api-reference/image-projects/face-swap-photo) — Face Swap Photo * [`POST /v1/head-swap`](/api-reference/image-projects/head-swap) — Head Swap * [`POST /v1/image-background-remover`](/api-reference/image-projects/image-background-remover) — Image Background Remover * [`POST /v1/photo-colorizer`](/api-reference/image-projects/photo-colorizer) — Photo Colorizer ## Audio projects * [`GET /v1/voices`](/api-reference/audio-projects/list-voices) lists the preset voices for speech generation. ### Manage projects * [`GET /v1/audio-projects/:id`](/api-reference/audio-projects/get-audio-details) — Get audio details * [`DELETE /v1/audio-projects/:id`](/api-reference/audio-projects/delete-audio) — Delete audio ### Create projects * [`POST /v1/ai-music-generator`](/api-reference/audio-projects/ai-music-generator) - AI Music Generator * [`POST /v1/ai-voice-generator`](/api-reference/audio-projects/ai-voice-generator) — AI Voice Generator * [`POST /v1/ai-voice-cloner`](/api-reference/audio-projects/ai-voice-cloner) — AI Voice Cloner # API Processing Times Source: https://docs.magichour.ai/api-reference/processing-times See the median time from project creation to completion for Magic Hour image, video, and audio jobs. > [!NOTE] > > **Measured November 3–30, 2026 (UTC)** > > This snapshot covers successful jobs submitted through the API or MCP during that window. The > records were read on December 2, 2026. Errors, cancellations, and still-active jobs are excluded. The median (p50) includes queue time. Half the successful jobs of each type finished within the time shown. Some API routes can create the same type of job. **Limited sample** means fewer than 30 successful jobs. Model, input size, duration, resolution, and queue load all affect processing time. Use these figures for planning and set timeouts for your own workload. ## Video endpoints | Endpoint | Median successful job | | :- | -: | | [`POST /v1/ai-talking-photo`](/api-reference/video-projects/ai-talking-photo) | 38s | | [`POST /v1/ai-ugc-ad`](/api-reference/video-projects/ai-ugc-ad-generator) | 24s | | [`POST /v1/ai-video-editor`](/api-reference/video-projects/ai-video-editor) | 56s | | [`POST /v1/ai-video-translator`](/api-reference/video-projects/ai-video-translator) | 35s (limited sample) | | [`POST /v1/ai-video-upscaler`](/api-reference/video-projects/ai-video-upscaler) | 1m 40s (limited sample) | | [`POST /v1/animation`](/api-reference/video-projects/animation) | 5m 19s | | [`POST /v1/audio-to-video`](/api-reference/video-projects/audio-to-video) | 41s | | [`POST /v1/auto-subtitle-generator`](/api-reference/video-projects/auto-subtitle-generator) | 1m 16s | | [`POST /v1/character-replace`](/api-reference/video-projects/character-replace) | 2m 27s | | [`POST /v1/face-swap`](/api-reference/video-projects/face-swap-video) | 1m 15s | | [`POST /v1/image-to-video`](/api-reference/video-projects/image-to-video) | 1m 13s | | [`POST /v1/lip-sync`](/api-reference/video-projects/lip-sync) | 1m 40s | | [`POST /v1/text-to-video`](/api-reference/video-projects/text-to-video) | 26s | | [`POST /v1/video-to-video`](/api-reference/video-projects/video-to-video) | 15m 37s | ## Image endpoints | Endpoint | Median successful job | | :- | -: | | [`POST /v1/ai-clothes-changer`](/api-reference/image-projects/ai-clothes-changer) | 6s | | [`POST /v1/ai-face-editor`](/api-reference/image-projects/ai-face-editor) | 2s | | [`POST /v1/ai-gif-generator`](/api-reference/image-projects/ai-gif-generator) | 23s | | [`POST /v1/ai-headshot-generator`](/api-reference/image-projects/ai-headshot-generator) | 7s | | [`POST /v1/ai-image-editor`](/api-reference/image-projects/ai-image-editor) | 18s | | [`POST /v1/ai-image-generator`](/api-reference/image-projects/ai-image-generator) | 7s | | [`POST /v1/ai-image-upscaler`](/api-reference/image-projects/ai-image-upscaler) | 23s | | [`POST /v1/ai-meme-generator`](/api-reference/image-projects/ai-meme-generator) | 7s | | [`POST /v1/ai-qr-code-generator`](/api-reference/image-projects/ai-qr-code-generator) | 6s | | [`POST /v1/body-swap`](/api-reference/image-projects/body-swap) | 24s | | [`POST /v1/face-swap-photo`](/api-reference/image-projects/face-swap-photo) | 4s | | [`POST /v1/head-swap`](/api-reference/image-projects/head-swap) | 7s | | [`POST /v1/image-background-remover`](/api-reference/image-projects/image-background-remover) | 5s | | [`POST /v1/photo-colorizer`](/api-reference/image-projects/photo-colorizer) | 6s | ## Audio endpoints | Endpoint | Median successful job | | :- | -: | | [`POST /v1/ai-music-generator`](/api-reference/audio-projects/ai-music-generator) | 28s | | [`POST /v1/ai-voice-generator`](/api-reference/audio-projects/ai-voice-generator) | 2s | | [`POST /v1/ai-voice-cloner`](/api-reference/audio-projects/ai-voice-cloner) | 10s | ## Monitor every job After creating a job, store its project ID and monitor the corresponding image, video, or audio project until it reaches a terminal status. * Prefer [webhooks](/integration/webhook/overview) for production and higher-volume integrations. * If polling, use [exponential backoff](/integration/adding-api-to-your-app#option-2-polling-good-for-simple-use-cases) instead of a tight fixed interval. * Handle `complete`, `error`, and `canceled` explicitly. Continue waiting while a job is `queued` or `rendering`. * Make webhook handlers idempotent and [verify every webhook signature](/integration/webhook/secure-handler). ## Choose timeouts for your product Do not use a typical time as a failure threshold. Set a user-facing timeout based on your product's tolerance for delayed work. Reaching that timeout should stop or defer your own waiting flow; it does not prove the Magic Hour job failed. Keep the project ID so you can check the final status later. Longer inputs, higher resolutions, and more complex video workflows generally need more time than small image jobs. Test the exact endpoints, models, settings, and input ranges your integration will use before choosing retry and timeout behavior. ## Investigate an unusually long job 1. Retrieve the project again and check its current status and error details. 2. Confirm the input file is valid and the account has enough credits. 3. Avoid submitting duplicate jobs while the original is still active. 4. If the job remains active beyond your workload-specific timeout, contact support with the project ID, endpoint, creation time, current status, and non-sensitive input details. [Learn how to monitor jobs and handle errors →](/integration/adding-api-to-your-app#step-3-monitor-job-status) # AI Talking Photo API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/ai-talking-photo post /v1/ai-talking-photo Animate a still portrait to speak an existing recording. Supply assets.image_file_path, assets.audio_file_path and the audio interval in start_seconds/end_seconds. Reuse the portrait's likeness and supplied audio performance; review both in the finished video. This API requires audio and does not synthesize speech from text. For existing video and replacement audio, use Lip Sync. For a prepared ad image and written script with synthesized dialogue, use AI UGC Ad Generator. Costs credits and returns a project ID; poll GET /v1/video-projects/{id} for status and downloads. Read the parameter definitions for generation-mode, duration, resolution and plan constraints. # AI UGC Ad Generator Source: https://docs.magichour.ai/api-reference/video-projects/ai-ugc-ad-generator post /v1/ai-ugc-ad Create a spoken presenter or ad video from a prepared image, approved script and end_seconds. Supply the image in assets.image_file_path. Synthesized dialogue is included; separate speech generation and lip sync are unnecessary for the same operation. Reuse an approved image directly; use Image Editor only for a requested visual change or a source problem that prevents the shot. For a supplied portrait and an existing recording whose performance must be preserved, use AI Talking Photo instead. Costs credits and returns a project ID; poll GET /v1/video-projects/{id} for status and downloads. Read the parameter definitions for model, script, duration, resolution and plan constraints. Review presenter/product likeness, spoken claims and the complete final word; exact voice matching is not promised. # AI Video Editor Source: https://docs.magichour.ai/api-reference/video-projects/ai-video-editor post /v1/ai-video-editor Edit an existing video with a text prompt. 1. Set `assets.video_file_path` to a direct video URL or the `file_path` from [Generate Upload URLs](https://docs.magichour.ai/api-reference/files/generate-asset-upload-urls). 2. Describe the edit in `style.prompt` and select the clip with `start_seconds` and `end_seconds`. The start time defaults to 0. 3. Use the returned `id` to [check the project](https://docs.magichour.ai/api-reference/video-projects/get-video-details) until its status is `complete`, then get the result from `downloads`. Credits are charged when the job is queued (`credits_charged` in the response). Failed jobs are refunded. See the [AI Video Editor](https://magichour.ai/products/ai-video-editor) for examples. # AI Video Translator Source: https://docs.magichour.ai/api-reference/video-projects/ai-video-translator post /v1/ai-video-translator Dub a source video's speech into a supported target language while preserving the speaker's voice and synchronizing lip movements. Supply assets.video_file_path, target_language and end_seconds; start_seconds selects the segment's start. Translation, voice preservation and lip sync are included in one operation, so separate voice cloning and lip-sync jobs are unnecessary for the same dub. For an already prepared replacement recording, use the Lip Sync API instead. Costs credits and returns a project ID; poll GET /v1/video-projects/{id} for status and downloads. Read the parameter definitions for current language, duration, resolution and plan constraints. Review translated meaning, voice likeness and lip timing in the finished video. # AI Video Upscaler Source: https://docs.magichour.ai/api-reference/video-projects/ai-video-upscaler post /v1/ai-video-upscaler **What this API does** Create the same Video Upscaler you can make in the browser, but programmatically, so you can automate it, run it at scale, or connect it to your own app or workflow. **Good for** - Automation and batch processing - Adding video upscaler into apps, pipelines, or tools **How it works (3 steps)** 1) Upload your inputs (video, image, or audio) with [Generate Upload URLs](https://docs.magichour.ai/api-reference/files/generate-asset-upload-urls) and copy the `file_path`. 2) Send a request to create a video upscaler job with the basic fields. 3) Check the job status until it's `complete`, then download the result from `downloads`. **Key options** - Inputs: usually a file, sometimes a YouTube link, depending on project type - Resolution: output size and plan requirements vary by workflow and model. Some workflows derive output size from the input video. - Extra fields: e.g. `face_swap_mode`, `start_seconds`/`end_seconds`, or a text prompt **Cost** Credits are charged when the job is queued (`credits_charged` in the response). Tools billed per frame charge an estimate and settle to the frames that actually render once the job finishes; tools billed per second charge the final amount upfront. Failed jobs are refunded. For detailed examples, see the [product page](https://magichour.ai/products/video-upscaler). # Animation API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/animation post /v1/animation Create a Animation video. The estimated frame cost is calculated based on the `fps` and `end_seconds` input. # Audio-to-Video Source: https://docs.magichour.ai/api-reference/video-projects/audio-to-video post /v1/audio-to-video **What this API does** Create the same Audio To Video you can make in the browser, but programmatically, so you can automate it, run it at scale, or connect it to your own app or workflow. **Good for** - Automation and batch processing - Adding audio to video into apps, pipelines, or tools **How it works (3 steps)** 1) Upload your inputs (video, image, or audio) with [Generate Upload URLs](https://docs.magichour.ai/api-reference/files/generate-asset-upload-urls) and copy the `file_path`. 2) Send a request to create a audio to video job with the basic fields. 3) Check the job status until it's `complete`, then download the result from `downloads`. **Key options** - Inputs: usually a file, sometimes a YouTube link, depending on project type - Resolution: output size and plan requirements vary by workflow and model. Some workflows derive output size from the input video. - Extra fields: e.g. `face_swap_mode`, `start_seconds`/`end_seconds`, or a text prompt **Cost** Credits are charged when the job is queued (`credits_charged` in the response). Tools billed per frame charge an estimate and settle to the frames that actually render once the job finishes; tools billed per second charge the final amount upfront. Failed jobs are refunded. For detailed examples, see the [product page](https://magichour.ai/products/audio-to-video). # Auto Subtitle Generator API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/auto-subtitle-generator post /v1/auto-subtitle-generator Generate an MP4 with burned-in captions in the video’s spoken language. Use the returned project ID with [Get video details](https://docs.magichour.ai/api-reference/video-projects/get-video-details). When the status is `complete`, download the video from `downloads[].url`. The API offers no SRT or VTT export. # Character Replace API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/character-replace post /v1/character-replace Recast a subject in existing footage or transfer its motion onto a reference character. Supply assets.video_file_path, assets.image_file_path and the selected start_seconds/end_seconds interval. style.mode replace substitutes the subject in the source scene; animate transfers the performance onto the reference image's character and composition. For face-only identity changes that retain the source body and clothing, use Face Swap Video instead. Costs credits and returns a project ID; poll GET /v1/video-projects/{id} for status and downloads. Read the parameter definitions for model-dependent duration, resolution, prompt direction and subject-selection controls. Review the intended subject, character likeness, action timing and scene continuity. # Delete Video API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/delete-video delete /v1/video-projects/{id} Permanently delete the rendered video. This action is not reversible, please be sure before deleting. # Estimate video credits Source: https://docs.magichour.ai/api-reference/video-projects/estimate-video-credits get /v1/estimate/video Get the credits a video create request charges when it is submitted. Pass `tool`, then the fields below that the tool's create request uses, with the same values. Tools billed per frame charge an estimate at submission, assuming 30 fps for an uploaded video, and settle to the frames that render. Does not create a project or spend credits. It prices the fields passed here. It does not check whether your plan allows the request, your balance or the rest of the create request. # Face Swap Video API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/face-swap-video post /v1/face-swap Replace facial identity in an existing video while retaining the source body, clothing, scene and performance. Supply assets.video_source, the matching video_file_path or youtube_url, and start_seconds/end_seconds. Use a replacement image for all-faces mode, or detected-face mappings for individual-faces mode. For whole-character recasting or motion transfer to a reference character, use Character Replace instead. Costs credits and returns a project ID; poll GET /v1/video-projects/{id} for status and downloads. Read the parameter definitions for face selection, version and plan constraints. Review identity, occlusions, temporal stability and whether other people remain unchanged. # Get Video Details API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/get-video-details get /v1/video-projects/{id} Check the progress of a video project. The `downloads` field is populated after a successful render. **Statuses** - `queued` — waiting to start - `rendering` — in progress - `complete` — ready; see `downloads` - `error` — a failure occurred (see `error`) - `canceled` — user canceled - `draft` — not used # Image-to-Video API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/image-to-video post /v1/image-to-video Animate a starting image. Set `assets.image_file_path` to a direct image file URL or the `file_path` from [Generate Upload URLs](https://docs.magichour.ai/api-reference/files/generate-asset-upload-urls). Set `end_seconds` for the clip length and use `style.prompt` to guide the motion. For models that support an end frame, set `assets.end_image_file_path` to the final image. Use the returned `id` to [check the project](https://docs.magichour.ai/api-reference/video-projects/get-video-details) until its status is `complete`, then get the result from `downloads`. Credits are charged when the job is queued (`credits_charged` in the response). Failed jobs are refunded. See [Image-to-Video](https://magichour.ai/products/image-to-video) for examples. # Lip Sync API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/lip-sync post /v1/lip-sync Match the lip movements in existing speaker footage to supplied replacement audio while retaining the source scene and performance. Supply assets.audio_file_path, assets.video_source, the matching video_file_path or youtube_url, and start_seconds/end_seconds. For a still portrait and recording, use AI Talking Photo. To translate the source speech while preserving the speaker's voice and synchronizing lips in one job, use AI Video Translator instead. Costs credits and returns a project ID; poll GET /v1/video-projects/{id} for status and downloads. Read the parameter definitions for generation-mode, source-video and plan constraints, then review mouth timing and complete speech in the result. # Text-to-Video API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/text-to-video post /v1/text-to-video Generate a video from a text prompt. A prompt-only request needs `style.prompt` and `end_seconds`. Some models also support media `references`. Use the returned `id` to [check the project](https://docs.magichour.ai/api-reference/video-projects/get-video-details) until its status is `complete`, then get the result from `downloads`. Credits are charged when the job is queued (`credits_charged` in the response). Failed jobs are refunded. See [Text-to-Video](https://magichour.ai/products/text-to-video) for examples. # Video-to-Video API Reference - Magic Hour Docs Source: https://docs.magichour.ai/api-reference/video-projects/video-to-video post /v1/video-to-video **What this API does** Create the same Video To Video you can make in the browser, but programmatically, so you can automate it, run it at scale, or connect it to your own app or workflow. **Good for** - Automation and batch processing - Adding video to video into apps, pipelines, or tools **How it works (3 steps)** 1) Upload your inputs (video, image, or audio) with [Generate Upload URLs](https://docs.magichour.ai/api-reference/files/generate-asset-upload-urls) and copy the `file_path`. 2) Send a request to create a video to video job with the basic fields. 3) Check the job status until it's `complete`, then download the result from `downloads`. **Key options** - Inputs: usually a file, sometimes a YouTube link, depending on project type - Resolution: output size and plan requirements vary by workflow and model. Some workflows derive output size from the input video. - Extra fields: e.g. `face_swap_mode`, `start_seconds`/`end_seconds`, or a text prompt **Cost** Credits are charged when the job is queued (`credits_charged` in the response). Tools billed per frame charge an estimate and settle to the frames that actually render once the job finishes; tools billed per second charge the final amount upfront. Failed jobs are refunded. For detailed examples, see the [product page](https://magichour.ai/products/video-to-video). V3 request example (upload both assets first): ```json {"start_seconds":0,"end_seconds":2,"width":1024,"height":704,"fps":30,"fps_resolution":"HALF","style":{"art_style":"Studio Ghibli","version":"v3","model":"default"},"assets":{"video_source":"file","video_file_path":"api-assets/id/video.mp4","initial_image_path":"api-assets/id/reference.png"}} ``` V3 supports up to 1,200 output frames for square videos and 800 otherwise. # Magic Hour API Pricing Source: https://docs.magichour.ai/billing/overview Understand API credits and choose a subscription or one-time credit packs with optional Auto Reload. ## How API Pricing Works Every generation uses credits. The number of credits depends on the model, output length, resolution, and other request options. See [models and credit costs](/api-reference/models) for the exact cost of each endpoint. You can fund API usage in two ways: * **Subscription plans** include prepaid credits and plan benefits for a fixed monthly or annual price. * **Credit packs** are one-time prepaid top-ups with no recurring subscription. Turn on [Auto Reload](#auto-reload) to buy packs automatically when your balance runs low. Unused prepaid credits from subscriptions and credit packs never expire. ## Choose a Payment Method | | Subscription plans | Credit packs | | :- | :- | :- | | **Payment timing** | Before use | Before use | | **Billing** | Monthly or annual | One-time purchase, or automatic with Auto Reload | | **Best for** | Predictable, ongoing usage | One-time work, occasional spikes, variable volume | | **Credits** | Included with each billing period | Added immediately | | **Unused credits** | Never expire | Never expire | | **Volume discounts** | Annual plan discount | Varies by active offer | | **Plan benefits** | Included | Watermark-free exports and commercial use | ### Subscription Plans Choose a plan when you want a predictable budget, recurring credits, and benefits such as larger uploads and higher web generation concurrency. API generations do not count toward web plan concurrency limits. Jobs may queue while server capacity becomes available. These are standard USD prices. Check the [pricing page](https://magichour.ai/pricing) and checkout for the offer and currency available to you. | Plan | Monthly | Annual equivalent | Credits per month | | :- | -: | -: | -: | | Creator | \$19 | \$12/month | 12,000 | | Pro | \$39 | \$25/month | 25,000 | | Business | \$99 | \$66/month | 70,000 | Annual Creator costs \$144 and includes 144,000 credits upfront. Annual Pro costs \$300, and annual Business costs \$792. Paid plans remove watermarks, include commercial use, and unlock higher-resolution options on each tool. Resolution is per tool, not a single pixel cap for the whole plan. See [resolution](/billing/resolution-limits). > [card] [Subscription Details](/billing/subscription-pricing) > > View plans, benefits, and annual pricing ### Credit Packs Buy credits once without starting a subscription. Packs work well for one-time projects, occasional usage, or temporary spikes. Credits are added immediately and never expire. In [Developer Hub → Analytics & Billing](https://magichour.ai/developer?tab=analytics-billing), choose **Buy credits** for a one-time purchase. Pack sizes, prices, and discounts vary by active offer. Check the pricing page and final checkout for the current offer. Credit packs include watermark-free exports and commercial use, subject to the [Terms of Service](https://magichour.ai/terms-of-service) and applicable content rights. A pack alone does not unlock models, resolutions, upload limits, or web concurrency reserved for a paid plan. ### Auto Reload Auto Reload buys credit packs for you when your balance runs low, so variable or high-volume API workloads keep running without manual top-ups. It works with or without a subscription. To turn it on, open **Pay as you go** in [Developer Hub → Analytics & Billing](https://magichour.ai/developer?tab=analytics-billing), or open **My Plan** in [Settings](https://magichour.ai/settings) and choose **Auto Reload**. Set a low-balance threshold and the **Credits per reload** to add. The reload must add at least as many credits as the threshold. You can also set an optional monthly spending limit. When your balance falls below the threshold, Auto Reload buys the credits using your saved payment method. If your balance is already below the threshold when you save, a reload starts right away and the credits appear once payment succeeds. You can change the settings or turn it off in the same place. Auto Reload starts a reload when you save the settings with your balance below the threshold, or when a charge leaves your balance below it. A rejected request is never charged, so it never starts a reload. Set the threshold to at least the cost of your largest request so a single large request is not rejected while your balance is still above the threshold. If a request is rejected for insufficient credits, call [`GET /v1/account`](/api-reference/account/get-account-details). While `auto_reload.status` is `auto_reload_pending`, check again shortly. Resubmit the request once `credits` covers its cost: the rejection's `credits_required`, or a [credit estimate](#run-a-credit-estimate) for the same request if the rejection omits it. If the balance is still short and no reload is pending, wait a few seconds and check again before you buy credits or lower the request cost. Two statuses mean Auto Reload is blocked until you act: * `payment_failed`: the last reload payment failed, and Auto Reload is paused. Update your payment method in [Settings](https://magichour.ai/settings) to resume it. * `spending_limit_reached`: the next reload would pass your monthly spending limit. Raise the limit in your Auto Reload settings, or buy credits manually until the next month. ## Estimate Your Cost 1. Check [models and credit costs](/api-reference/models), or estimate a request without spending credits. Use `GET /v1/estimate/image`, `GET /v1/estimate/video`, or `GET /v1/estimate/audio`. See the [image estimate API reference](/api-reference/image-projects/estimate-image-credits), [video estimate API reference](/api-reference/video-projects/estimate-video-credits), or [audio estimate API reference](/api-reference/audio-projects/estimate-audio-credits). The estimate uses the pricing fields you send. It does not verify plan access or balance. For video tools billed by the frame, the submission estimate may differ from the final charge. 2. Multiply by your expected monthly generations, including higher-resolution or longer outputs. 3. Use the [API cost calculator](https://magichour.ai/api?ref=docs-billing-overview#api-cost-calculator) to estimate your credit use and compare subscriptions with credit packs. > [!NOTE] > > **Not sure?** Start with the Free tier. Starter credits and account-specific rewards may be > available; check your account balance, then choose a payment method after measuring real usage. ### Run a credit estimate [Set your API key](/get-started/authentication#using-api-keys), then copy a request below. These examples return 5 credits for one image, 120 for a five-second video, and 12 for 120 characters of speech. Change the fields to match the request you plan to send. ```bash Image theme={null} curl -fsS --get "https://api.magichour.ai/v1/estimate/image" \ -H "Authorization: Bearer $MAGIC_HOUR_API_KEY" \ --data-urlencode "tool=ai-image-generator" \ --data-urlencode "model=z-image-turbo" \ --data-urlencode "resolution=640px" \ --data-urlencode "image_count=1" ``` ```bash Video theme={null} curl -fsS --get "https://api.magichour.ai/v1/estimate/video" \ -H "Authorization: Bearer $MAGIC_HOUR_API_KEY" \ --data-urlencode "tool=text-to-video" \ --data-urlencode "model=ltx-2.5" \ --data-urlencode "resolution=480p" \ --data-urlencode "end_seconds=5" \ --data-urlencode "audio=true" ``` ```bash Speech theme={null} curl -fsS --get "https://api.magichour.ai/v1/estimate/audio" \ -H "Authorization: Bearer $MAGIC_HOUR_API_KEY" \ --data-urlencode "tool=ai-voice-generator" \ --data-urlencode "character_count=120" ``` ## Make your first API request [Create an API key](https://magichour.ai/developer?tab=api-keys\&ref=docs-billing-overview\&utm_source=docs\&utm_medium=referral\&utm_campaign=billing), then follow the [quickstart](/get-started/quick-start) to generate an image or video. The [account endpoint](/api-reference/account/get-account-details) returns your credit balance and subscription details so you can check them before submitting a job. # Resolution Limits Source: https://docs.magichour.ai/billing/resolution-limits How plan tier and per-request resolution work across Magic Hour APIs. Resolution is per tool. Your plan does not set one pixel size for every endpoint. It gates which resolution options a given tool will accept. On newer endpoints you pick a named resolution, and higher values cost more credits on the same plan. ## Named resolutions (the current model) [Text to video](/api-reference/video-projects/text-to-video) and [image to video](/api-reference/video-projects/image-to-video) take `360p`, `480p`, `720p`, `1080p`, or `4k`. [Image generator](/api-reference/image-projects/ai-image-generator) and [image editor](/api-reference/image-projects/ai-image-editor) take `640px`, `1k`, `2k`, or `4k`. What you can pass depends on two things: the model, and your plan. * **The model** lists its supported resolutions. `minimax-h3` supports 480p, 720p and 1080p. `kling-3.0` goes up to 4K. See [models](/api-reference/models). * **Your plan** gates the highest option you may request. Free is typically the lowest option (`480p` / `640px`). Paid plans (Creator, Pro, Business) can request the higher options the model supports. You pay more credits for higher resolution; the plan does not charge a flat "Creator rate" regardless of size. A Creator using `kling-3.0` pays 72 credits per second at 1080p or 264 at 4K. These are the base rates for requests without audio or a video reference. > [!NOTE] > > With no resolution or legacy quality override, Text to Video and Image to Video use `480p` on Free > when `model` is omitted or set to `default`. The other requests default to `720p`. On Free, pass > `480p` explicitly when choosing a model that supports it. Image `auto` is deprecated and mapped > server-side to a resolution the model and your plan both support. ## Plan vs cost | Plan | What you can request | What you pay | | :- | :- | :- | | Free | Lowest option on each tool, plus the models marked free | That option's credit cost | | Creator | Higher options the model supports | The selected resolution's credit cost | | Pro | Same named-resolution access as other paid plans | Same, at the selected resolution | | Business | Same named-resolution access as other paid plans | Same, at the selected resolution | Creator, Pro, and Business also differ on credits per month, upload size, concurrency, and support. They do not each lock you to a single pixel size on these endpoints. Full per-model rates are on [models and credit costs](/api-reference/models). ## Tools that still cap longest edge Some older image and video endpoints still use a longest-edge pixel cap. Treat these as tool-specific, not as the plan's identity. | Plan | Typical longest edge | | :- | :- | | Free | 576px | | Creator | 1024px | | Pro | 1472px | | Business | 4096px | A few of those tools also have a hard cap regardless of plan: AI Headshot Generator (1344px), AI Clothes Changer (about 1MP), AI Talking Photo (720p), Video to Video and Animation (1472px). Video to Video additionally requires width and height divisible by 64. Those caps are shrinking in importance as more tools move to named resolutions. ## Upgrading Upgrade when you need a resolution option Free does not unlock, or when higher-resolution jobs are burning through the monthly allotment and the next plan's credit volume is cheaper than packs. [Pricing](https://magichour.ai/pricing?ref=docs-resolution-limits) lists current plans. > [card] [View Pricing Plans](/billing/subscription-pricing) > > Compare all subscription tiers and their benefits # Subscription Pricing Source: https://docs.magichour.ai/billing/subscription-pricing Get credits upfront with predictable monthly or yearly billing and discounted annual plans. ## How Subscription Pricing Works **Simple concept:** Pay upfront for a set amount of credits that you can use throughout your subscription period. Perfect for predictable usage patterns. ### **The Basics** 1. **Choose your plan** based on monthly credit volume and which resolution options you need 2. **Select billing frequency** - monthly or yearly (annual billing is discounted) 3. **Pay upfront** and receive all credits immediately 4. **Use credits anytime** - credits never expire, even after subscription ends 5. **Auto-renewal** ensures continuous access (can be cancelled anytime) ### **Key Benefits** ✅ **Predictable costs** - Know exactly what you'll pay each month/year ✅ **Credits upfront** - Get all your credits immediately to use anytime ✅ **Yearly savings** - Annual billing is discounted ✅ **No usage tracking** - Use credits at your own pace ✅ **Higher resolution options** - Paid plans unlock higher-resolution choices on each tool ### **How Payment Methods Differ** | Subscription plans | Credit packs | | :- | :- | | Recurring monthly or annual payment | One-time purchase, or automatic with Auto Reload | | Credits and plan benefits included | Credits without a subscription | | Prepaid credits never expire | Prepaid credits never expire | | Best for predictable, ongoing usage | Best for one-time work, top-ups, or variable volume | ## Choose Your Plan Higher plans include more credits each month, larger uploads, and more concurrent web generations. API generations do not count toward web plan concurrency limits. Jobs may queue while server capacity becomes available. Resolution is per tool: paid plans unlock higher-resolution options, and requesting those options costs more credits. See [resolution](/billing/resolution-limits). > [card] Free > [card] Creator > [card] Pro > [card] Business These are standard USD prices. Check the [pricing page](https://magichour.ai/pricing) and checkout for the offer and currency available to you. Annual plans include twelve months of credits upfront. Creator costs \$144 for 144,000 credits, Pro costs \$300 for 300,000 credits, and Business costs \$792 for 840,000 credits. ### Kling 3.0 annual pricing example A five-second `kling-3.0` video at `720p`, with audio off and no video reference, uses 300 credits. Creator annual costs \$144 upfront and covers 480 such clips at \$0.30 per clip when all included credits are used. | Annual plan | Upfront payment | Included credits | 720p, audio off | 720p, audio on | 1080p, audio off | 1080p, audio on | | :- | -: | -: | -: | -: | -: | -: | | Creator | \$144/year | 144,000 | \$0.300 | \$0.420 | \$0.360 | \$0.540 | | Pro | \$300/year | 300,000 | \$0.300 | \$0.420 | \$0.360 | \$0.540 | | Business | \$792/year | 840,000 | \$0.283 | \$0.396 | \$0.339 | \$0.509 | These are effective subscription allocations per five-second generation, rounded to three decimal places and assuming full use of the included credits. They are not standalone per-video purchases. Annual payment is due upfront; tax and additional credit packs are excluded. Audio and resolution change the credit cost; video-reference inputs use a separate rate. See [models and credit costs](/api-reference/models#video-credit-costs) before choosing settings. Live checkout is on the [pricing page](https://magichour.ai/pricing?ref=docs-subscription-pricing). ## Need More Credits? If you use more credits than your plan includes, you can purchase additional credit packs anytime. ### **Credit Packs** Pack sizes, prices, and discounts vary by active offer. Check the [pricing page](https://magichour.ai/pricing#credit-pack) and final checkout for the current offer. Credits are added immediately and never expire. Packs include watermark-free exports and commercial use, subject to the [Terms of Service](https://magichour.ai/terms-of-service) and applicable content rights. A pack alone does not unlock models, resolutions, upload limits, or web concurrency reserved for a paid plan. ### **When to Buy Credit Packs** * **Seasonal spikes** in usage * **One-time projects** requiring extra credits * **Testing higher usage** before upgrading plans * **End-of-month** credit shortfall > [!NOTE] > > **Tip:** If you consistently need credit packs, consider upgrading to the next plan tier for > better value. ## Choosing a Plan Pick the plan whose monthly credits cover your expected volume, then check that it unlocks the resolution options you need. Higher resolution on the same plan costs more credits, so a 1080p workload burns through an allotment faster than 480p. If you regularly exhaust your allowance and buy credit packs, the next tier up is usually cheaper than the packs. For API workloads with variable volume, turn on [Auto Reload](/billing/overview#auto-reload) so credit packs are bought automatically when your balance runs low. ## Getting Started Ready to subscribe? Here's how to set up your subscription in minutes. **1. Visit the Pricing Page** Go to [magichour.ai/pricing](https://magichour.ai/pricing?ref=docs-subscription-pricing) to see all available plans and current pricing. **2. Choose Billing Frequency** **Monthly**: Pay monthly, cancel anytime. **Yearly**: Pay upfront at the discount shown on the live pricing page. **3. Select Your Plan** Choose based on monthly credits and which resolution options you need: * **Creator**: \$19/month for 12,000 credits, or \$144/year for 144,000 credits upfront * **Pro**: $39/month ($25/month billed annually), 25,000 credits * **Business**: $99/month ($66/month billed annually), 70,000 credits Click the button for your chosen plan to proceed to checkout. **4. Complete Payment** Enter your payment information using any of these secure methods: - **Credit/Debit Cards**: Visa, Mastercard, American Express, Discover - **Digital Wallets**: Apple Pay, Google Pay - **Regional Options**: AliPay and other methods depending on your location All payments are processed securely through Stripe. Review your plan details and click **"Subscribe"**. **5. Access Your Credits** After successful payment: * You'll be redirected to [Settings](https://magichour.ai/settings) * Credits are added to your account within minutes * Start using the API immediately ![Payment Successful](https://mintcdn.com/magichour/zDVRebwg0vCIeSNP/billing/images/subscription-successful.png?fit=max\&auto=format\&n=zDVRebwg0vCIeSNP\&q=85\&s=40959ead03d963952705d03bcec319e0) ## Managing Your Subscription ### **Tracking Credit Usage** Monitor your remaining credits in multiple ways: 1. **Settings**: Visit [Settings](https://magichour.ai/settings) to see your monthly credit allocation and next renewal date 2. **Any signed-in page**: Check credit balance in the top navigation ![Create Page](https://mintcdn.com/magichour/zDVRebwg0vCIeSNP/billing/images/subscription-credits.png?fit=max\&auto=format\&n=zDVRebwg0vCIeSNP\&q=85\&s=00d81ca0b450f926f94ae4a817a3a4bf) ### **Subscription Management** **Upgrade Options**: * **Immediate upgrade**: New plan starts right away, billing cycle resets * **End-of-cycle upgrade**: Change takes effect at next billing date **Downgrade Process**: * On the signed-in [Pricing page](https://magichour.ai/pricing), choose the lower paid plan, then **Change at renewal**. Review the renewal date before confirming; your current plan stays active until then. * **Start \[plan] now** instead charges the full target-plan price and starts a new billing period, without proration. Review the amount first. Your existing credits stay in your account. * Cancel renewal only to end the paid subscription. **Other Management**: * **Cancel anytime**: Access continues until period ends * **Billing frequency**: Switch between monthly/yearly anytime * **Auto-renewal**: Automatically renews unless cancelled ### **What Happens When You Downgrade or Cancel** When your subscription ends or you downgrade to Free: **✅ You Keep:** * **All unused credits** - they carry over permanently * **API access** - continue making requests with remaining credits * **Account history** - all your generated content remains accessible * **Credit-pack benefits** - if you have purchased a credit pack, watermark-free exports and commercial-use rights remain available under the Terms of Service and applicable content rights **❌ You Lose (at end of billing cycle):** * **Higher resolution options** - revert to the Free option on each tool * **Subscription-only watermark removal** - accounts without a credit-pack purchase may receive watermarks, depending on the tool * **Monthly credit allocation** - starter credits and rewards vary by account; check your current balance * **Premium features** - lose priority support, larger uploads, etc. **💡 Upgrade Anytime:** * **Immediate upgrade**: New benefits start right away, billing resets * **End-of-cycle upgrade**: Changes take effect at next billing date * Your existing credits work at higher resolutions again ### **Important Notes** > [!WARNING] > > **Insufficient Credits**: API calls will be rejected if your account doesn't have enough credits > for the requested operation. > [!NOTE] > > **Credits Never Expire**: Your credits remain in your account permanently, even after your > subscription ends. Subscription-only benefits, such as higher-resolution options, end with the > subscription. Credit-pack purchases retain watermark-free exports and commercial-use rights under > the Terms of Service and applicable content rights. > [!TIP] > > **Usage Monitoring**: Set up alerts in your dashboard to get notified when credits are running > low. # Authentication Source: https://docs.magichour.ai/get-started/authentication Create and manage API keys to authenticate your requests to the Magic Hour API. ## Overview Magic Hour uses API keys to authenticate requests. Your API keys carry many privileges, so be sure to keep them secure! Do not share your secret API keys in publicly accessible areas such as GitHub, client-side code, and so forth. All API requests must be authenticated by including your API key in the `Authorization` header: ```bash theme={null} Authorization: Bearer your_api_key_here ``` ## Creating Your First API Key **1. Sign in to Magic Hour** Visit [magichour.ai](https://magichour.ai/sign-up?utm_source=docs\&utm_medium=referral\&utm_campaign=authentication) and sign in to your account. If you don't have an account yet, you can create one for free. ![Sign in page](https://mintcdn.com/magichour/jj1tYAcivRE8aZA_/get-started/images/sign-in-to-magic-hour.jpg?fit=max\&auto=format\&n=jj1tYAcivRE8aZA_\&q=85\&s=3704d89dd82ddf3caf3d1eb5c559b237) **2. Navigate to Developer Hub** Once signed in, go directly to the [API Keys section of the Developer Hub](https://magichour.ai/developer?tab=api-keys\&ref=docs-authentication\&utm_source=docs\&utm_medium=referral\&utm_campaign=authentication). ![Developer Hub with API Keys](https://mintcdn.com/magichour/jj1tYAcivRE8aZA_/get-started/images/navigate-to-developer-hub.jpg?fit=max\&auto=format\&n=jj1tYAcivRE8aZA_\&q=85\&s=6c57bb8db62ebdd324c32e4752aea5f4) **3. Create New API Key** Click the **"Create API Key"** button to generate a new key. ![Create API Key button](https://mintcdn.com/magichour/jj1tYAcivRE8aZA_/get-started/images/create-new-api-key.jpg?fit=max\&auto=format\&n=jj1tYAcivRE8aZA_\&q=85\&s=eb4243d87433148524a35f864cd67600) **4. Configure Your API Key** Give your API key a descriptive name to help you identify its purpose later: * **Name**: Choose a clear name (e.g., "Production App", "Development Testing", "Mobile App") ![API Key configuration](https://mintcdn.com/magichour/jj1tYAcivRE8aZA_/get-started/images/configure-your-api-key.jpg?fit=max\&auto=format\&n=jj1tYAcivRE8aZA_\&q=85\&s=42c65e5410b7a5289fa18a6de9753860) Click **"Create Key"** to generate your new API key. **5. Copy and Store Your API Key** **Important**: Your API key will only be shown once. Copy it immediately and store it securely. ![API Key created](https://mintcdn.com/magichour/jj1tYAcivRE8aZA_/get-started/images/copy-and-store-api-key.jpg?fit=max\&auto=format\&n=jj1tYAcivRE8aZA_\&q=85\&s=8680e299f848c4ede67cc6184a15d3f4) > [!WARNING] > > **Save your API key now!** You won't be able to see the full key again after closing this dialog. If you lose it, you'll need to create a new one. ## Managing Your API Keys ### Viewing API Keys In the Developer Hub, you can see all your API keys with: * **Name**: The descriptive name you gave the key * **Last 4 Characters**: The last 4 characters of the key * **Created**: When the key was created ![API Keys list](https://mintcdn.com/magichour/jj1tYAcivRE8aZA_/get-started/images/managing-your-api-keys.jpg?fit=max\&auto=format\&n=jj1tYAcivRE8aZA_\&q=85\&s=adc387d0090d0d9d2f523a17e3ba53be) ### Revoking API Keys To revoke an API key: 1. Find the key in your API Keys list 2. Click the **Delete (Trash Icon)** button next to the key 3. Click "Delete key" to confirm the revocation ![Revoke API Key](https://mintcdn.com/magichour/jj1tYAcivRE8aZA_/get-started/images/revoking-api-keys.jpg?fit=max\&auto=format\&n=jj1tYAcivRE8aZA_\&q=85\&s=1188aa2945e5de10e26474c0ecdec50c) > [!WARNING] > > **Immediate Effect**: Revoked keys stop working immediately. Any applications using the revoked > key will start receiving authentication errors. ### Rotating API Keys For security best practices, regularly rotate your API keys: 1. **Create a new API key** with the same permissions 2. **Update your applications** to use the new key 3. **Test thoroughly** to ensure everything works 4. **Revoke the old key** once you're confident the new key is working ## Using API Keys Set `MAGIC_HOUR_API_KEY` in your environment as shown below. The cURL example calls [Get account details](/api-reference/account/get-account-details) so you can verify the key without spending credits. A successful response includes your `tier` and available `credits`. Keep the account response private. ### In Code ```python Python SDK theme={null} from magic_hour import Client import os client = Client(token=os.environ["MAGIC_HOUR_API_KEY"]) ``` ```javascript Node.js SDK theme={null} import { Client } from "magic-hour"; const token = process.env.MAGIC_HOUR_API_KEY; if (!token) throw new Error("Set MAGIC_HOUR_API_KEY first."); const client = new Client({ token }); ``` ```bash cURL theme={null} curl -fsS "https://api.magichour.ai/v1/account" \ -H "Authorization: Bearer ${MAGIC_HOUR_API_KEY:?Set MAGIC_HOUR_API_KEY first.}" ``` ### Environment Variables Store your API key as an environment variable for security: ```bash .env file theme={null} MAGIC_HOUR_API_KEY=your_api_key_here ``` ```bash Shell Export theme={null} export MAGIC_HOUR_API_KEY=your_api_key_here ``` ```bash Windows theme={null} set MAGIC_HOUR_API_KEY=your_api_key_here ``` ## Security Best Practices ### ✅ Do * **Store keys securely** in environment variables or secure key management systems * **Use different keys** for different environments (development, staging, production) * **Rotate keys regularly** (every 90 days recommended) * **Revoke unused keys** immediately * **Monitor key usage** in the Developer Hub * **Implement proper error handling** for authentication failures ### ❌ Don't * **Never commit keys** to version control (Git, SVN, etc.) * **Don't expose keys** in client-side code (JavaScript, mobile apps) * **Don't share keys** via email, chat, or other insecure channels * **Don't use production keys** in development environments * **Don't ignore security warnings** about exposed keys ### Key Storage Solutions **For Development:** * Environment variables (`.env` files) * Local configuration files (excluded from version control) **For Production:** * AWS Secrets Manager * Azure Key Vault * Google Secret Manager * HashiCorp Vault * Kubernetes Secrets ## Authentication Errors Common authentication errors and how to resolve them: ### `401 Unauthorized` **Cause**: Invalid or missing API key **Solutions**: * Check that your API key is correct * Ensure the `Authorization` header is properly formatted * Verify the key hasn't been revoked ## Monitoring Usage Check your account's credit balance with [`GET /v1/account`](/api-reference/account/get-account-details). The balance covers all API keys on the account, so compare it against the requests you expect to have sent. This helps you: * Detect unusual activity that might indicate a compromised key * Plan for capacity and billing ## Next Steps > [card] [Quick Start Guide](/get-started/quick-start) > > Make your first API call with your new API key > [card] [Google Colab Cookbook](https://colab.research.google.com/drive/1NTHL_lr_s-qBJ-mSecSXPzRLi9_V5JiU?usp=sharing) > > Try the Magic Hour APIs with ready-to-run sample code. Just add your API key. > [card] [SDKs](/integration/adding-api-to-your-app) > > Use official SDKs for easier integration > [card] [Pricing](/billing/overview) > > Understand how API usage affects billing > [card] [Webhooks](/integration/webhook/overview) > > Set up webhooks for real-time notifications ## Need Help? If you're having trouble with authentication: * Check our [troubleshooting guide](/get-started/quick-start#troubleshooting) * Contact support at [support@magichour.ai](mailto:support@magichour.ai) * Join our community on [Discord](https://discord.gg/JX5rgsZaJp) > [!NOTE] > > **Security Concern?** If you believe your API key has been compromised, revoke it immediately in > the Developer Hub and create a new one. # Bulk Face Swap API: Safe Batch Processing Source: https://docs.magichour.ai/get-started/bulk-face-swap Process photo face swaps in a bounded batch with Python, JavaScript, or Bash while preserving project IDs and avoiding duplicate charges. Use one permitted source face across a list of target photos while keeping a durable record of every request. This workflow fits opt-in event photos, personalized creative, and photo-editing products. Magic Hour processes one photo project per API request; there is no bulk face-swap endpoint. The runners below call the companion single-photo script sequentially, wait for each result, and stop on the first error. Start with one image before running a batch. > [card] [Face Swap API page](https://magichour.ai/api/face-swap) > > Explore Face Swap API capabilities and pricing > [card] [Face Swap Photo reference](/api-reference/image-projects/face-swap-photo) > > Check request fields and response schemas ## Before you start 1. [Create an API key](https://magichour.ai/developer?tab=api-keys) and set `MAGIC_HOUR_API_KEY`. 2. Download the matching companion worker from this guide's [versioned source](https://github.com/magichourhq/docs/tree/e5d62a0e81205cb1241480a73584dc30622e10c5/examples/bulk-face-swap): `example.py`, `example.mjs`, or `example.sh`. These workers read `SOURCE_FACE_URL` and `TARGET_IMAGE_URL`, print `PROJECT_ID` before polling, and support `PROJECT_ID` recovery. 3. Run that example with one source and one target. Confirm the output and credit charge before continuing. 4. Create `targets.txt` beside the script with one direct HTTPS target-image URL per line. Use 1-100 images for the first batch. 5. Set `SOURCE_FACE_URL` to a clear source image you control. Only process images and likenesses you have permission to use. > [!WARNING] > > Every fresh create request uses generation credits. A timed-out client can hide an accepted job; > preserve its log and reconcile the project before retrying. ## Source, target, and cost `source_file_path` supplies the face identity. `target_file_path` supplies the scene and faces to replace. With `face_swap_mode: "all-faces"`, every detected target face receives the same identity. For different identities in a group photo, use [face detection](/api-reference/files/face-detection) and individual face mappings instead. Photo face swap costs 10 credits per image, so 10 completed photos cost 100 credits and 100 cost 1,000 credits. A completed image that you reject creatively still uses credits. Check current [billing options](/billing/overview) before scaling. ## Run a bounded batch Save the matching runner below as `batch.py`, `batch.mjs`, or `batch.sh`, then run it from the same folder as the single-photo example and `targets.txt`. ```python Python theme={null} # Download this guide's companion example.py first. # targets.txt: one direct target image URL per line, up to 100 images. import os from pathlib import Path import subprocess import sys targets = [line.strip() for line in Path("targets.txt").read_text().splitlines() if line.strip()] if not 1 <= len(targets) <= 100: raise SystemExit("Start with 1–100 target images") if not os.environ.get("SOURCE_FACE_URL") or not os.environ.get("MAGIC_HOUR_API_KEY"): raise SystemExit("Set SOURCE_FACE_URL and MAGIC_HOUR_API_KEY") Path("batch-logs").mkdir(exist_ok=True) for index, target in enumerate(targets): log = Path(f"batch-logs/{index:03d}.log") complete = log.with_suffix(".complete") if complete.exists(): if not log.exists(): raise SystemExit(f"Completion marker is missing its log: {complete}") print(log, "already complete") continue # A log without a completion marker means submitted OR uncertain. if log.exists(): raise SystemExit(f"Review existing log before continuing: {log}") env = dict(os.environ, TARGET_IMAGE_URL=target) env.pop("PROJECT_ID", None) with log.open("x") as output: result = subprocess.run([sys.executable, "example.py"], env=env, stdout=output, stderr=subprocess.STDOUT) if result.returncode != 0: print(log, "needs review") raise SystemExit(result.returncode) # Reconcile before submitting more. complete.touch(exist_ok=False) print(log, "complete") ``` ```javascript JavaScript theme={null} // Download this guide's companion example.mjs first. // Save this as batch.mjs; run: node batch.mjs import { readFileSync, mkdirSync, existsSync, openSync, closeSync } from "node:fs"; import { spawnSync } from "node:child_process"; const targets = readFileSync("targets.txt", "utf8") .split(/\r?\n/) .map((s) => s.trim()) .filter(Boolean); if (targets.length < 1 || targets.length > 100) throw new Error("Start with 1–100 images"); if (!process.env.SOURCE_FACE_URL || !process.env.MAGIC_HOUR_API_KEY) { throw new Error("Set SOURCE_FACE_URL and MAGIC_HOUR_API_KEY"); } mkdirSync("batch-logs", { recursive: true }); for (const [index, target] of targets.entries()) { const log = "batch-logs/" + String(index).padStart(3, "0") + ".log"; const complete = log.slice(0, -4) + ".complete"; if (existsSync(complete)) { if (!existsSync(log)) throw new Error("Completion marker is missing its log: " + complete); console.log(log, "already complete"); continue; } if (existsSync(log)) throw new Error("Review existing log before continuing: " + log); const env = { ...process.env, TARGET_IMAGE_URL: target }; delete env.PROJECT_ID; const fd = openSync(log, "wx"); const result = spawnSync(process.execPath, ["example.mjs"], { env, stdio: ["ignore", fd, fd] }); closeSync(fd); if (result.status !== 0) { console.log(log, "needs review"); process.exit(result.status ?? 1); } const completeFd = openSync(complete, "wx"); closeSync(completeFd); console.log(log, "complete"); } ``` ```bash curl / Bash theme={null} #!/usr/bin/env bash # Download this guide's companion example.sh first. # targets.txt: one direct target image URL per line. Run: bash batch.sh set -euo pipefail : "${SOURCE_FACE_URL:?Set SOURCE_FACE_URL}" : "${MAGIC_HOUR_API_KEY:?Set MAGIC_HOUR_API_KEY}" target_count=$(sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' targets.txt \ | awk 'length($0) > 0 { count++ } END { print count + 0 }') if [ "$target_count" -lt 1 ] || [ "$target_count" -gt 100 ]; then echo "Start with 1–100 target images" >&2 exit 1 fi mkdir -p batch-logs index=0 while IFS= read -r target || [ -n "$target" ]; do target=$(printf '%s' "$target" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') [ -z "$target" ] && continue log=$(printf 'batch-logs/%03d.log' "$index") complete=$(printf 'batch-logs/%03d.complete' "$index") index=$((index + 1)) if [ -e "$complete" ]; then if [ ! -e "$log" ]; then echo "Completion marker is missing its log: $complete" >&2; exit 1; fi echo "$log already complete" continue fi if [ -e "$log" ]; then echo "Review existing log before continuing: $log" >&2; exit 1; fi # Reserve the log before POST; never overwrite an uncertain submission. (set -o noclobber; : > "$log") if env -u PROJECT_ID TARGET_IMAGE_URL="$target" bash example.sh > "$log" 2>&1; then (set -o noclobber; : > "$complete") echo "$log complete" else echo "$log needs review" exit 1 fi done < targets.txt ``` ## Expected result Each `batch-logs/000.log` file contains the project ID, final charge, and expiring download URL, or the error that needs review. A matching `.complete` marker appears only after the single-photo script exits successfully. A log without a completion marker stops the batch so an uncertain submission is not silently repeated. To resume, use the same source face and keep `targets.txt` unchanged. The runner uses row numbers to find completed items. If you change either input, reconcile any pending jobs in the original folder before starting the new batch in a separate folder. Download each completed output before its URL expires. Keep failed, timed-out, and completed work in distinct states. ## Recover an interrupted item If a log contains a project ID, set `PROJECT_ID` to that ID and rerun the single-photo script to resume polling without another create request. Append its output to the same log. After it exits successfully and you verify that the result belongs to the target, create the matching marker without overwriting an existing one: ```bash theme={null} python3 -c 'from pathlib import Path; Path("batch-logs/001.complete").touch(exist_ok=False)' ``` Replace `001` with the reconciled log index. The next batch run skips that item and continues. If the log has no project ID after a timeout, do not submit the request again. Email [support@magichour.ai](mailto:support@magichour.ai) with the `POST /v1/face-swap-photo` endpoint, request name, and UTC timestamp so the request can be traced first. Preserve the original logs; deleting them and rerunning the whole list can create duplicate charges. For a larger workload, replace these local runners with a durable job queue, bounded concurrency, webhook signature verification, and explicit per-item state in your database. ## Troubleshooting | Problem | What to do | | :- | :- | | `401` | Verify the API key and Bearer header. Keep keys in server environment variables. | | Invalid input | Use direct file URLs or uploaded paths. Photo requests use `source_file_path` and `target_file_path`. | | `429` or a transient polling failure | Reduce concurrency, back off, and resume the existing project ID. Do not blindly retry create requests. | | No face detected | Use a clear, front-facing source face and target images with visible faces. | | A log exists without `.complete` | Reconcile that job before continuing. Do not delete the log to bypass the stop. | This guide handles photos. [Video face swap](/api-reference/video-projects/face-swap-video) has duration-based costs and longer processing times. For motion from a product photo, use the [product-video recipe](/get-started/starter-recipes). # API Cookbook - Google Colab Source: https://docs.magichour.ai/get-started/cookbook Try the Magic Hour APIs with ready-to-run sample code. ## Overview The Magic Hour API Cookbook is a comprehensive Google Colab notebook containing working examples for the most popular Magic Hour APIs. Simply add your API key and start experimenting with: * All video tools (Animation, Face Swap, Lip Sync, etc.) * All image tools (Image Generator, Face Editor, Upscaler, etc.) * All audio tools (Voice Generator) > [card] [Open Google Colab Cookbook](https://colab.research.google.com/drive/1NTHL_lr_s-qBJ-mSecSXPzRLi9_V5JiU?usp=sharing) > > Launch the notebook in Google Colab. Just add your API key and run any example. ## What's Included The cookbook includes: * **Working code samples** for the most popular APIs * **Pre-configured parameters** optimized for fast execution * **Error handling** examples * **Best practices** and tips ## Getting Started 1. **Get your API key** - If you haven't already, [create an API key](https://magichour.ai/developer?tab=api-keys) 2. **Open the notebook** - Click the link above to open in Google Colab 3. **Add your API key** - Set it in the first cell 4. **Run any example** - Execute any code cell to try that API > [!TIP] > > **No installation required:** Google Colab runs Python in your browser with all dependencies > pre-installed. ## Related Resources > [card] [Product Video and Lip-Sync Recipes](/get-started/starter-recipes) > > Run two focused Python workflows with your own local files, from upload to downloaded video. > [card] [Quick Start](/get-started/quick-start) > > Step-by-step guide to your first API call > [card] [API Reference](/api-reference) > > Complete API documentation # Magic Hour API Quickstart Source: https://docs.magichour.ai/get-started/quick-start Generate and download your first Magic Hour image in the browser, from your terminal, or in code. ## Choose your path > [card] [Try the API in your browser](https://magichour.ai/developer?tab=playground\&tool=ai-image-generator\&ref=docs-quickstart-playground\&utm_source=docs\&utm_medium=referral\&utm_campaign=quick-start) > > Sign in and run an image request in the API Playground. > [card] [Build with code](#1-create-your-api-key) > > Create a key and follow the SDK or cURL example below. > [card] [MCP setup guide](/integration/model-context-protocol) > > Use Magic Hour from Claude, ChatGPT, Claude Code, or Codex through MCP. Prefer your terminal? [Use the CLI](#generate-from-your-terminal) to generate and download an image without writing SDK code. Before generating, check [model credit costs](/api-reference/models), your [credit balance](/api-reference/account/get-account-details), and [API billing options](/billing/overview). **For the SDK path, you'll:** 1. **Create an API key** - Get credentials to authenticate with our API 2. **Set up your development environment** - Install SDK and create project files 3. **Generate your first output** - Make an API call and download the result > [!NOTE] > > **Credit Cost:** Pick the example that matches your goal. The image tab costs about 5 credits; the > face swap video tab costs about 200 credits for the sample clip. New accounts may receive starter > credits and account-specific rewards; check your balance in the web app. **Want to generate a video first?** Create a free API key below, then use the [Text-to-Video example](/tools/video/text-to-video#basic-text-to-video) if you're starting from a prompt or the [Image-to-Video recipe](/get-started/starter-recipes#choose-a-model-for-product-video) if you have a photo. Both examples make a five-second clip with LTX 2.5 at 480p for 120 credits. Those settings work on the Free plan when your account has enough credits. ## 1. Create your API key **Why:** API keys authenticate your requests and track your usage. 1. Open the [API Keys section of the Developer Hub](https://magichour.ai/developer?tab=api-keys\&ref=docs-quickstart\&utm_source=docs\&utm_medium=referral\&utm_campaign=quick-start) and sign in. 2. Click **Create key**, give it a name (e.g., "My First Project"), and create it. 3. **Copy the API key immediately** — you won't be able to see it again. > [card] [Need the full walkthrough?](/get-started/authentication#creating-your-first-api-key) > > See screenshots and key-management guidance in the Authentication guide. Store your API key as an environment variable: ```bash macOS/Linux theme={null} export MAGIC_HOUR_API_KEY="your_api_key_here" ``` ```cmd Windows theme={null} set MAGIC_HOUR_API_KEY=your_api_key_here ``` ```powershell PowerShell theme={null} $env:MAGIC_HOUR_API_KEY = "your_api_key_here" ``` > [!WARNING] > > **Never commit API keys to version control.** Always use environment variables or secure > credential management. A new key's full secret is shown only when it is created; if you lose it, > create another key instead of trying to recover it from the Developer Hub. ## 2. Set up your development environment **Why:** SDKs handle authentication, polling, and file downloads automatically, reducing boilerplate code. Using cURL? [Skip to the code examples](#copy-the-code-and-run-it). ### Create your project directory ```bash Python theme={null} # Create and navigate to project directory mkdir magic-hour-quickstart cd magic-hour-quickstart ``` ```bash Node.js theme={null} # Create and navigate to project directory mkdir magic-hour-quickstart cd magic-hour-quickstart # Initialize npm project npm init -y # Enable ES module support for this example npm pkg set type=module ``` ```bash Go theme={null} # Create and navigate to project directory mkdir magic-hour-quickstart cd magic-hour-quickstart # Initialize Go module go mod init magic-hour-quickstart ``` ```bash Rust theme={null} # Create new Rust project cargo new magic-hour-quickstart cd magic-hour-quickstart # Install the runtime and download dependencies used by the examples below cargo add tokio@1 --features macros,rt-multi-thread cargo add reqwest@0.12 --features blocking ``` ### Install the SDK If you already have a Python virtual environment, use its Python to install the SDK and run `main.py`. Otherwise, create `.venv` in your project folder. ```bash Python (macOS/Linux) theme={null} python3 -m venv .venv .venv/bin/python -m pip install --upgrade magic_hour ``` ```powershell Python (Windows) theme={null} py -m venv .venv .\.venv\Scripts\python.exe -m pip install --upgrade magic_hour ``` ```sh Node SDK theme={null} npm install magic-hour ``` ```sh Go SDK theme={null} go get -u github.com/magichourhq/magic-hour-go/client ``` ```sh Rust SDK theme={null} cargo add magic_hour ``` **Rust on Linux:** Install OpenSSL development headers and `pkg-config` before building. On Ubuntu/Debian, run `sudo apt-get install pkg-config libssl-dev`. See the [OpenSSL setup guide](https://docs.rs/openssl/latest/openssl/#automatic) for other Linux distributions. > [!TIP] > > Want to test your integration without spending credits? The SDKs include a [mock > server](/integration/development-and-testing#mock-server-recommended-for-development) that returns > sample responses instantly. ## 3. Generate your first output **What we're doing:** Submit a generation job, wait for Magic Hour to render it, then download the result. Choose the example that matches what you want to build: | Example | Best for | Typical cost | Typical wait | | :- | :- | :- | :- | | **Generate image** | Cheapest first success | 5 credits | 5-30 seconds | | **Face swap video** | Our most popular API path | \~200 credits for the sample clip | 2-5 minutes | Use the [AI Image Generator reference](/api-reference/image-projects/ai-image-generator) to check exact request fields. To get a finished image, follow these three steps: 1. **Request accepted:** Creating an image returns a project ID and `credits_charged`. This is not a completed image yet. 2. **Queued or rendering:** [Check the image project's status](/api-reference/image-projects/get-image-details) until it is `complete`, `error`, or `canceled`. The Python and Node.js examples use the SDK to check the project and download the result. The other examples show how to pause between status checks. 3. **Result ready:** On `complete`, use the returned download URL (or the SDK's downloaded file) and check the charged credits. `error` and `canceled` are terminal states, not download-ready results. ### Copy the code and run it For cURL, use Bash with cURL 7.76 or later and `jq` installed, and set `MAGIC_HOUR_API_KEY`. > [!NOTE] > > **SDK compatibility:** Install or upgrade the current Python or Node.js SDK before running these > examples. Older SDKs may provide `generate()` but not support the `model`, aspect ratio, and > resolution fields used below. Go and Rust use the manual create/poll/download pattern shown below. 1. **Choose an example tab**, then copy the code from your preferred language tab below. > [tab] Generate image (\~5 credits) > > Create an image from a text prompt. This is the cheapest way to verify your setup end to end. > > See the [image generation guide](/tools/image/image-generator) for prompt examples and the > [Image Generator API reference](/api-reference/image-projects/ai-image-generator) for every request field. > > **Why these parameters:** > > * `image_count: 1` - Generate one image (costs 5 credits) > * `model: "z-image-turbo"` - Use a specific model available on Free and paid plans > * `aspect_ratio: "16:9"` - Widescreen (landscape) output; also supports `1:1` and `9:16` > * `resolution: "640px"` - Use the resolution available on every plan instead of deprecated `auto` > * `wait_for_completion: true` - SDK polls until done > * `download_outputs: true` - Automatically download to local disk > * `download_directory: "."` - Save to the current directory > > ```python Python SDK theme={null} > from magic_hour import Client > import os > > # Use environment variable for security > client = Client(token=os.getenv("MAGIC_HOUR_API_KEY")) > > project_id = os.getenv("MAGIC_HOUR_PROJECT_ID") > if not project_id: > project = client.v1.ai_image_generator.create( > image_count=1, > model="z-image-turbo", > aspect_ratio="16:9", > resolution="640px", > style={ > "prompt": "Epic anime art of wizard casting a cosmic spell in the sky that says 'Magic Hour'" > }, > ) > project_id = project.id > > print(f"Project ID: {project_id}", flush=True) > > result = client.v1.image_projects.check_result( > id=project_id, > wait_for_completion=True, > download_outputs=True, > download_directory=".", > max_wait_seconds=180, > ) > > if result.status != "complete" or not result.downloaded_paths: > raise RuntimeError( > f"Project {project_id} did not save an output (status: {result.status}). " > "Retrieve this project before creating another request." > ) > > print(f"Saved outputs for project {project_id}. This project used {result.credits_charged} credits. Files: {result.downloaded_paths}") > ``` > > ```typescript Node SDK theme={null} > import { Client } from "magic-hour"; > > // Use environment variable for security > const client = new Client({ token: process.env.MAGIC_HOUR_API_KEY }); > > async function main() { > let projectId = process.env.MAGIC_HOUR_PROJECT_ID; > if (!projectId) { > const project = await client.v1.aiImageGenerator.create({ > imageCount: 1, > model: "z-image-turbo", > aspectRatio: "16:9", > resolution: "640px", > style: { > prompt: "Epic anime art of wizard casting a cosmic spell in the sky that says 'Magic Hour'", > }, > }); > projectId = project.id; > } > > console.log(`Project ID: ${projectId}`); > > const result = await client.v1.imageProjects.checkResult( > { id: projectId }, > { > waitForCompletion: true, > downloadOutputs: true, > downloadDirectory: ".", > maxWaitSeconds: 180, > } > ); > > if (result.status !== "complete" || !result.downloadedPaths?.length) { > throw new Error( > `Project ${projectId} did not save an output (status: ${result.status}). Retrieve this project before creating another request.` > ); > } > > console.log( > `Saved outputs for project ${projectId}. This project used ${result.creditsCharged} credits. Files: ${result.downloadedPaths}` > ); > } > > main(); > ``` > > ```go Go SDK theme={null} > package main > > import ( > "fmt" > "io" > "log" > "net/http" > "os" > "path/filepath" > "time" > > sdk "github.com/magichourhq/magic-hour-go/client" > nullable "github.com/magichourhq/magic-hour-go/nullable" > "github.com/magichourhq/magic-hour-go/resources/v1/ai_image_generator" > "github.com/magichourhq/magic-hour-go/resources/v1/image_projects" > "github.com/magichourhq/magic-hour-go/types" > ) > > func main() { > // Use environment variable for security > client := sdk.NewClient( > sdk.WithBearerAuth(os.Getenv("MAGIC_HOUR_API_KEY")), > sdk.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}), > ) > projectID := os.Getenv("MAGIC_HOUR_PROJECT_ID") > if projectID == "" { > createRes, err := client.V1.AiImageGenerator.Create(ai_image_generator.CreateRequest{ > ImageCount: 1, > Model: nullable.NewValue(types.V1AiImageGeneratorCreateBodyModelEnumZImageTurbo), > AspectRatio: nullable.NewValue(types.V1AiImageGeneratorCreateBodyAspectRatioEnum169), > Resolution: nullable.NewValue(types.V1AiImageGeneratorCreateBodyResolutionEnum640px), > Style: types.V1AiImageGeneratorCreateBodyStyle{ > Prompt: "Epic anime art of wizard casting a cosmic spell in the sky that says 'Magic Hour'", > }, > }) > > if err != nil { > log.Fatal(err) > } > > projectID = createRes.Id > fmt.Printf("queued image with id %s, spent %d credits\n", createRes.Id, createRes.CreditsCharged) > } else { > fmt.Printf("Checking project %s\n", projectID) > } > > for deadline := time.Now().Add(3 * time.Minute); time.Now().Before(deadline); { > res, err := client.V1.ImageProjects.Get(image_projects.GetRequest{Id: projectID}) > if err != nil { > log.Fatal(err) > } > if res.Status == "complete" { > println("render complete!") > if len(res.Downloads) == 0 || res.Downloads[0].Url == "" { > log.Fatalf("No download URL for project %s. Retrieve that project again.", projectID) > } > url := res.Downloads[0].Url > outputFile := "output.png" > > resp, err := (&http.Client{Timeout: 120 * time.Second}).Get(url) > if err != nil { > log.Fatal(err) > } > defer resp.Body.Close() > > if resp.StatusCode < 200 || resp.StatusCode >= 300 { > log.Fatalf("download failed: HTTP %d; retrieve the same project again for a fresh URL\n", resp.StatusCode) > } > > out, err := os.CreateTemp(filepath.Dir(outputFile), ".magichour-*.part") > if err != nil { > log.Fatal(err) > } > > _, saveErr := io.Copy(out, resp.Body) > closeErr := out.Close() > if saveErr == nil { > saveErr = closeErr > } > if saveErr == nil { > saveErr = os.Rename(out.Name(), outputFile) > } > if saveErr != nil { > _ = os.Remove(out.Name()) > log.Fatalf("download failed for project %s: %v", projectID, saveErr) > } > fmt.Printf("file downloaded successfully to %s\n", outputFile) > return > } else if res.Status == "error" || res.Status == "canceled" { > log.Fatalf("Project %s ended with status %s.", projectID, res.Status) > } else { > fmt.Printf("render in progress: %s\n", res.Status) > time.Sleep(1 * time.Second) > } > } > log.Fatalf("Stopped waiting for project %s. Check its status before submitting another job.", projectID) > } > ``` > > ```rust Rust SDK theme={null} > use magic_hour; > use reqwest; > > #[tokio::main] > async fn main() { > // Use environment variable for security > let api_key = std::env::var("MAGIC_HOUR_API_KEY") > .expect("MAGIC_HOUR_API_KEY environment variable not set"); > let http_client = reqwest::Client::builder() > .timeout(std::time::Duration::from_secs(30)) > .build() > .expect("Build HTTP client"); > let mut client = magic_hour::Client::default() > .with_client(http_client) > .with_bearer_auth(&api_key); > > let create_res = client > .v1() > .ai_image_generator() > .create(magic_hour::resources::v1::ai_image_generator::CreateRequest { > image_count: 1, > model: Some(magic_hour::models::V1AiImageGeneratorCreateBodyModelEnum::ZImageTurbo), > aspect_ratio: Some(magic_hour::models::V1AiImageGeneratorCreateBodyAspectRatioEnum::Enum169), > resolution: Some(magic_hour::models::V1AiImageGeneratorCreateBodyResolutionEnum::Enum640px), > style: magic_hour::models::V1AiImageGeneratorCreateBodyStyle { > prompt: "Epic anime art of wizard casting a cosmic spell in the sky that says 'Magic Hour'".to_string(), > ..Default::default() > }, > ..Default::default() > }) > .await > .unwrap(); > let project_id = create_res.id; > let credits_charged = create_res.credits_charged; > println!("queued image with id {project_id}, spent {credits_charged} credits"); > let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180); > while std::time::Instant::now() < deadline { > let res = client > .v1() > .image_projects() > .get(magic_hour::resources::v1::image_projects::GetRequest { > id: project_id.clone(), > }) > .await > .unwrap(); > match res.status { > magic_hour::models::V1ImageProjectsGetResponseStatusEnum::Complete => { > println!("render complete!"); > let url = res.downloads > .first() > .expect("Completed project has no download URL. Retrieve the same project again.") > .url.clone(); > > tokio::task::block_in_place(move || { > let mut response = reqwest::blocking::get(url).unwrap(); > let output_path = "output.png"; > if response.status().is_success() { > let partial_path = format!("{output_path}.{}.part", std::process::id()); > let mut output_file = std::fs::OpenOptions::new() > .write(true) > .create_new(true) > .open(&partial_path) > .unwrap(); > let copied = std::io::copy(&mut response, &mut output_file); > drop(output_file); > if let Err(error) = copied.and_then(|_| std::fs::rename(&partial_path, output_path)) { > let _ = std::fs::remove_file(&partial_path); > panic!("Failed to save {output_path}: {error}"); > } > println!("file downloaded successfully to {}", output_path); > } else { > eprintln!("Failed to download file: {}. Retrieve the same project again.", response.status()); > std::process::exit(1); > } > }); > > return; > } > magic_hour::models::V1ImageProjectsGetResponseStatusEnum::Error > | magic_hour::models::V1ImageProjectsGetResponseStatusEnum::Canceled => { > eprintln!("Project {project_id} ended with status {}.", res.status); > std::process::exit(1); > } > _ => { > println!("render in progress: {}", res.status); > std::thread::sleep(std::time::Duration::from_secs(1)); > } > } > } > eprintln!("Stopped waiting for project {project_id}. Check its status before submitting another job."); > std::process::exit(1); > } > ``` > > ```sh cURL theme={null} > #!/bin/bash > set -e > > for dependency in curl jq; do > command -v "$dependency" >/dev/null 2>&1 || { > echo "Install $dependency before running this example." >&2 > exit 1 > } > done > : "${MAGIC_HOUR_API_KEY:?Set MAGIC_HOUR_API_KEY before running this example.}" > > URL="https://api.magichour.ai/v1/ai-image-generator" > STATUS_URL="https://api.magichour.ai/v1/image-projects" > # Use environment variable for security > API_KEY="$MAGIC_HOUR_API_KEY" > OUTPUT_PATH="output.png" > > project_id="${MAGIC_HOUR_PROJECT_ID:-}" > if [ -z "$project_id" ]; then > create_response=$(curl --fail-with-body -sS --max-time 30 "$URL" \ > --request POST \ > --header "Content-Type: application/json" \ > --header "Authorization: Bearer $API_KEY" \ > --data '{ > "image_count": 1, > "model": "z-image-turbo", > "aspect_ratio": "16:9", > "resolution": "640px", > "style": { > "prompt": "Epic anime art of wizard casting a cosmic spell in the sky that says \"Magic Hour\"" > } > }') || { > printf '%s\n' "$create_response" >&2 > exit 1 > } > > project_id=$(echo "$create_response" | jq -er '.id') > credits_charged=$(echo "$create_response" | jq -r '.credits_charged') > > echo "queued image with id $project_id, spent $credits_charged credits" > else > echo "Checking project $project_id" > fi > > deadline=$((SECONDS + 180)) > while (( SECONDS < deadline )); do > status_response=$(curl -fsS --max-time 15 "$STATUS_URL/$project_id" --header "Authorization: Bearer $API_KEY") > > status=$(echo "$status_response" | jq -r '.status') > > if [ "$status" == "complete" ]; then > download_url=$(jq -er '.downloads[0].url | strings | select(length > 0)' <<< "$status_response") || { > echo "No download URL for project $project_id. Retrieve that project again." >&2 > exit 1 > } > partial_path="$OUTPUT_PATH.$$.part" > curl -fsS --max-time 60 "$download_url" -o "$partial_path" > mv "$partial_path" "$OUTPUT_PATH" > echo "render complete!" > echo "file downloaded successfully to $OUTPUT_PATH" > exit 0 > elif [ "$status" == "error" ] || [ "$status" == "canceled" ]; then > echo "Project $project_id ended with status $status." >&2 > exit 1 > else > echo "render in progress" > sleep 1 > fi > done > echo "Stopped waiting for project $project_id. Check its status before submitting another job." >&2 > exit 1 > ``` > > **Expected output for Python and Node.js:** > > ``` > Saved outputs for project clx1234567890. This project used 5 credits. Files: ['./output-0.png'] > ``` > > **Expected output for Go, Rust, and cURL:** > > ``` > queued image with id clx1234567890, spent 5 credits > render complete! > file downloaded successfully to output.png > ``` > [tab] Face swap video (\~200 credits) > > Swap a face into a video clip. This is our most popular API path. The sample uses a 6.2-second > segment (`start_seconds` to `end_seconds`). Video pricing is duration-based, so longer clips cost > more. > > ```python Python SDK theme={null} > from magic_hour import Client > import os > > # Use environment variable for security > client = Client(token=os.getenv("MAGIC_HOUR_API_KEY")) > > project_id = os.getenv("MAGIC_HOUR_PROJECT_ID") > if not project_id: > project = client.v1.face_swap.create( > name="Swap Tom Cruise into Iron Man scene", > assets={ > "image_file_path": "https://videos.magichour.ai/api-assets/sample/tom-cruise.png", > "video_file_path": "https://videos.magichour.ai/api-assets/sample/iron-man.mp4", > "video_source": "file", > }, > start_seconds=2.3, > end_seconds=8.5, > ) > project_id = project.id > > print(f"Project ID: {project_id}", flush=True) > > result = client.v1.video_projects.check_result( > id=project_id, > wait_for_completion=True, > download_outputs=True, > download_directory=".", > max_wait_seconds=600, > ) > > if result.status != "complete" or not result.downloaded_paths: > raise RuntimeError( > f"Project {project_id} did not save an output (status: {result.status}). " > "Retrieve this project before creating another request." > ) > > print(f"Saved outputs for project {project_id}. This project used {result.credits_charged} credits. Files: {result.downloaded_paths}") > ``` > > ```typescript Node SDK theme={null} > import { Client } from "magic-hour"; > > // Use environment variable for security > const client = new Client({ token: process.env.MAGIC_HOUR_API_KEY }); > > async function main() { > let projectId = process.env.MAGIC_HOUR_PROJECT_ID; > if (!projectId) { > const project = await client.v1.faceSwap.create({ > name: "Swap Tom Cruise into Iron Man scene", > assets: { > imageFilePath: "https://videos.magichour.ai/api-assets/sample/tom-cruise.png", > videoFilePath: "https://videos.magichour.ai/api-assets/sample/iron-man.mp4", > videoSource: "file", > }, > startSeconds: 2.3, > endSeconds: 8.5, > }); > projectId = project.id; > } > > console.log(`Project ID: ${projectId}`); > > const result = await client.v1.videoProjects.checkResult( > { id: projectId }, > { > waitForCompletion: true, > downloadOutputs: true, > downloadDirectory: ".", > maxWaitSeconds: 600, > } > ); > > if (result.status !== "complete" || !result.downloadedPaths?.length) { > throw new Error( > `Project ${projectId} did not save an output (status: ${result.status}). Retrieve this project before creating another request.` > ); > } > > console.log( > `Saved outputs for project ${projectId}. This project used ${result.creditsCharged} credits. Files: ${result.downloadedPaths}` > ); > } > > main(); > ``` > > ```go Go SDK theme={null} > package main > > import ( > "fmt" > "io" > "log" > "net/http" > "os" > "path/filepath" > "time" > > sdk "github.com/magichourhq/magic-hour-go/client" > nullable "github.com/magichourhq/magic-hour-go/nullable" > "github.com/magichourhq/magic-hour-go/resources/v1/face_swap" > "github.com/magichourhq/magic-hour-go/resources/v1/video_projects" > "github.com/magichourhq/magic-hour-go/types" > ) > > func main() { > // Use environment variable for security > client := sdk.NewClient( > sdk.WithBearerAuth(os.Getenv("MAGIC_HOUR_API_KEY")), > sdk.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}), > ) > projectID := os.Getenv("MAGIC_HOUR_PROJECT_ID") > if projectID == "" { > createRes, err := client.V1.FaceSwap.Create(face_swap.CreateRequest{ > Name: nullable.NewValue("Swap Tom Cruise into Iron Man scene"), > Assets: types.V1FaceSwapCreateBodyAssets{ > ImageFilePath: nullable.NewValue("https://videos.magichour.ai/api-assets/sample/tom-cruise.png"), > VideoFilePath: nullable.NewValue("https://videos.magichour.ai/api-assets/sample/iron-man.mp4"), > VideoSource: types.V1FaceSwapCreateBodyAssetsVideoSourceEnumFile, > }, > StartSeconds: 2.3, > EndSeconds: 8.5, > }) > if err != nil { > log.Fatal(err) > } > > projectID = createRes.Id > fmt.Printf("queued video with id %s, spent %d estimated credits. The final charge is available after rendering.\n", createRes.Id, createRes.CreditsCharged) > } else { > fmt.Printf("Checking project %s\n", projectID) > } > > for deadline := time.Now().Add(10 * time.Minute); time.Now().Before(deadline); { > res, err := client.V1.VideoProjects.Get(video_projects.GetRequest{Id: projectID}) > if err != nil { > log.Fatal(err) > } > if res.Status == "complete" { > fmt.Printf("render complete! Final credits charged is %d, actual fps is %f.\n", res.CreditsCharged, res.Fps) > if len(res.Downloads) == 0 || res.Downloads[0].Url == "" { > log.Fatalf("No download URL for project %s. Retrieve that project again.", projectID) > } > url := res.Downloads[0].Url > outputFile := "output.mp4" > > resp, err := (&http.Client{Timeout: 120 * time.Second}).Get(url) > if err != nil { > log.Fatal(err) > } > defer resp.Body.Close() > > if resp.StatusCode < 200 || resp.StatusCode >= 300 { > log.Fatalf("download failed: HTTP %d; retrieve the same project again for a fresh URL\n", resp.StatusCode) > } > > out, err := os.CreateTemp(filepath.Dir(outputFile), ".magichour-*.part") > if err != nil { > log.Fatal(err) > } > > _, saveErr := io.Copy(out, resp.Body) > closeErr := out.Close() > if saveErr == nil { > saveErr = closeErr > } > if saveErr == nil { > saveErr = os.Rename(out.Name(), outputFile) > } > if saveErr != nil { > _ = os.Remove(out.Name()) > log.Fatalf("download failed for project %s: %v", projectID, saveErr) > } > fmt.Printf("file downloaded successfully to %s\n", outputFile) > return > } else if res.Status == "error" || res.Status == "canceled" { > log.Fatalf("Project %s ended with status %s.", projectID, res.Status) > } else { > fmt.Printf("render in progress: %s\n", res.Status) > time.Sleep(1 * time.Second) > } > } > log.Fatalf("Stopped waiting for project %s. Check its status before submitting another job.", projectID) > } > ``` > > ```rust Rust SDK theme={null} > use magic_hour; > use reqwest; > > #[tokio::main] > async fn main() { > // Use environment variable for security > let api_key = std::env::var("MAGIC_HOUR_API_KEY") > .expect("MAGIC_HOUR_API_KEY environment variable not set"); > let http_client = reqwest::Client::builder() > .timeout(std::time::Duration::from_secs(30)) > .build() > .expect("Build HTTP client"); > let mut client = magic_hour::Client::default() > .with_client(http_client) > .with_bearer_auth(&api_key); > > let create_res = client > .v1() > .face_swap() > .create(magic_hour::resources::v1::face_swap::CreateRequest { > name: Some("Swap Tom Cruise into Iron Man scene".to_string()), > assets: magic_hour::models::V1FaceSwapCreateBodyAssets { > image_file_path: Some( > "https://videos.magichour.ai/api-assets/sample/tom-cruise.png".to_string(), > ), > video_file_path: Some( > "https://videos.magichour.ai/api-assets/sample/iron-man.mp4".to_string(), > ), > video_source: magic_hour::models::V1FaceSwapCreateBodyAssetsVideoSourceEnum::File, > ..Default::default() > }, > start_seconds: 2.3, > end_seconds: 8.5, > ..Default::default() > }) > .await > .unwrap(); > let project_id = create_res.id; > let credits_charged = create_res.credits_charged; > println!("queued face swap video with id {project_id}, spent {credits_charged} estimated credits. The final charge is available after rendering."); > > let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600); > while std::time::Instant::now() < deadline { > let res = client > .v1() > .video_projects() > .get(magic_hour::resources::v1::video_projects::GetRequest { > id: project_id.clone(), > }) > .await > .unwrap(); > match res.status { > magic_hour::models::V1VideoProjectsGetResponseStatusEnum::Complete => { > println!( > "render complete! Final credit charged is {}, actual fps is {}", > res.credits_charged, res.fps > ); > let url = res.downloads > .first() > .expect("Completed project has no download URL. Retrieve the same project again.") > .url.clone(); > > tokio::task::block_in_place(move || { > let mut response = reqwest::blocking::get(url).unwrap(); > let output_path = "output.mp4"; > if response.status().is_success() { > let partial_path = format!("{output_path}.{}.part", std::process::id()); > let mut output_file = std::fs::OpenOptions::new() > .write(true) > .create_new(true) > .open(&partial_path) > .unwrap(); > let copied = std::io::copy(&mut response, &mut output_file); > drop(output_file); > if let Err(error) = copied.and_then(|_| std::fs::rename(&partial_path, output_path)) { > let _ = std::fs::remove_file(&partial_path); > panic!("Failed to save {output_path}: {error}"); > } > println!("file downloaded successfully to {}", output_path); > } else { > eprintln!("Failed to download file: {}. Retrieve the same project again.", response.status()); > std::process::exit(1); > } > }); > > return; > } > magic_hour::models::V1VideoProjectsGetResponseStatusEnum::Error > | magic_hour::models::V1VideoProjectsGetResponseStatusEnum::Canceled => { > eprintln!("Project {project_id} ended with status {}.", res.status); > std::process::exit(1); > } > _ => { > println!("render in progress: {}", res.status); > std::thread::sleep(std::time::Duration::from_secs(1)); > } > } > } > eprintln!("Stopped waiting for project {project_id}. Check its status before submitting another job."); > std::process::exit(1); > } > ``` > > ```sh cURL theme={null} > #!/bin/bash > set -e > > for dependency in curl jq; do > command -v "$dependency" >/dev/null 2>&1 || { > echo "Install $dependency before running this example." >&2 > exit 1 > } > done > : "${MAGIC_HOUR_API_KEY:?Set MAGIC_HOUR_API_KEY before running this example.}" > > URL="https://api.magichour.ai/v1/face-swap" > STATUS_URL="https://api.magichour.ai/v1/video-projects" > # Use environment variable for security > API_KEY="$MAGIC_HOUR_API_KEY" > OUTPUT_PATH="output.mp4" > > project_id="${MAGIC_HOUR_PROJECT_ID:-}" > if [ -z "$project_id" ]; then > create_response=$(curl --fail-with-body -sS --max-time 30 "$URL" \ > --request POST \ > --header "Content-Type: application/json" \ > --header "Authorization: Bearer $API_KEY" \ > --data '{ > "name": "Swap Tom Cruise into Iron Man scene", > "assets": { > "image_file_path": "https://videos.magichour.ai/api-assets/sample/tom-cruise.png", > "video_file_path": "https://videos.magichour.ai/api-assets/sample/iron-man.mp4", > "video_source": "file" > }, > "start_seconds": 2.3, > "end_seconds": 8.5 > }') || { > printf '%s\n' "$create_response" >&2 > exit 1 > } > > project_id=$(echo "$create_response" | jq -er '.id') > credits_charged=$(echo "$create_response" | jq -r '.credits_charged') > > echo "queued face swap video with id $project_id, spent $credits_charged estimated credits. The final charge is available after rendering." > else > echo "Checking project $project_id" > fi > > deadline=$((SECONDS + 600)) > while (( SECONDS < deadline )); do > status_response=$(curl -fsS --max-time 15 "$STATUS_URL/$project_id" --header "Authorization: Bearer $API_KEY") > > status=$(echo "$status_response" | jq -r '.status') > > if [ "$status" == "complete" ]; then > credits_charged=$(echo "$status_response" | jq -r '.credits_charged') > fps=$(echo "$status_response" | jq -r '.fps') > download_url=$(jq -er '.downloads[0].url | strings | select(length > 0)' <<< "$status_response") || { > echo "No download URL for project $project_id. Retrieve that project again." >&2 > exit 1 > } > echo "render complete! Final credit charged is $credits_charged, actual fps is $fps." > partial_path="$OUTPUT_PATH.$$.part" > curl -fsS --max-time 120 "$download_url" -o "$partial_path" > mv "$partial_path" "$OUTPUT_PATH" > echo "Saved $OUTPUT_PATH" > exit 0 > elif [ "$status" == "error" ] || [ "$status" == "canceled" ]; then > echo "Project $project_id ended with status $status." >&2 > exit 1 > else > echo "render in progress: $status" > sleep 3 > fi > done > echo "Stopped waiting for project $project_id. Check its status before submitting another job." >&2 > exit 1 > ``` > > **Expected output for Python and Node.js:** > > ``` > Saved outputs for project clx1234567890. This project used 186 credits. Files: ['./output.mp4'] > ``` 2. **Save the code.** Use `main.py` for Python, `main.js` for Node.js, `main.go` for Go, or `src/main.rs` for Rust. For cURL, save it as `generate.sh` in your current directory. 3. **Run the code from that directory.** If you open a new terminal, return to that directory and set `MAGIC_HOUR_API_KEY` there before running the command. ```bash Python (macOS/Linux) theme={null} .venv/bin/python main.py ``` ```powershell Python (Windows) theme={null} .\.venv\Scripts\python.exe main.py ``` ```bash Node.js theme={null} node main.js ``` ```bash Go theme={null} go run main.go ``` ```bash Rust theme={null} cargo run ``` ```bash cURL theme={null} bash generate.sh ``` If a Python, Node.js, Go, or cURL example stops after printing a project ID, set `MAGIC_HOUR_PROJECT_ID` to that ID and run the same example again. It checks the existing project and downloads the result when it is ready. Clear the variable before starting a new project. For Rust, use the printed ID with [Get Image Details](/api-reference/image-projects/get-image-details) or [Get Video Details](/api-reference/video-projects/get-video-details). If the create request times out before it returns an ID, check your [library](https://magichour.ai/my-library). For production integrations, [use an idempotency key for safe retries](/integration/adding-api-to-your-app#safe-retries-with-idempotency-keys) when you first submit the request. ## Generate from your terminal Install `mh` using the [CLI installation instructions](https://github.com/magichourhq/magic-hour-cli#install) for macOS, Linux, or Windows. Then sign in through your browser and check your account and credits: ```sh theme={null} mh login mh whoami ``` > [!WARNING] > > Each generation creates a new project and uses credits. The command below requests one > `z-image-turbo` image at `640px`, currently 5 credits. Check your balance before running it. > Stopping the command does not cancel a submitted project. ```sh theme={null} mh image generate --prompt "A mountain landscape at sunrise" --model z-image-turbo --resolution 640px --count 1 ``` The CLI waits for completion, downloads the image into your current directory, and prints its path and project ID. No SDK project or manual polling loop is needed. If waiting or downloading is interrupted, keep the project ID printed by the CLI. Recover the same project instead of running the generation command again: ```sh theme={null} mh image wait PROJECT_ID mh image download PROJECT_ID ``` Replace `PROJECT_ID` with your existing image project ID. These commands do not create another generation. An errored or canceled project cannot be resumed this way. If creation times out before returning an ID, check Images in your [Library](https://magichour.ai/my-library) before retrying. If the download stopped after saving some files, create a new empty directory and run `mh image download PROJECT_ID --output RECOVERY_DIR` with that directory's path. ## Troubleshooting ### Common Issues **FileNotFoundError when using a custom `download_directory`** The SDK saves outputs into `download_directory` but does **not** create the folder for you. The default (`"."`) always works. If you point it at a folder that doesn't exist yet (e.g. `"outputs"`), create it first: ```bash theme={null} mkdir outputs ``` **Error: MAGIC_HOUR_API_KEY environment variable not set** **Solution:** Set your API key as an environment variable. See [Environment Variables](/get-started/authentication#environment-variables) in the Authentication guide for platform-specific setup steps. ### HTTP Error Codes If you encounter HTTP errors, here's what they mean: | Error Code | Meaning | Solution | | :- | :- | :- | | `400` | Bad Request | The response `message` names the invalid or missing field - fix it and resubmit | | `401` | Unauthorized | Verify your API key is correct and sent as `Authorization: Bearer ` | | `402` | Payment Required | Use the response `code` to add credits, start a subscription, or upgrade the plan | | `404` | Not Found | Check the route and project ID | | `422` | Unprocessable Entity | Change the request values before retrying | | `500` | Internal Server Error | Retry status reads for the same project ID. Before retrying a create request, check whether it was accepted; contact support if uncertain. | For a `402`, use the response's structured `code` to choose the next step. * If you get `insufficient_credits`, check `credits_required`, `credits_available`, and `credit_shortfall` when present. On Image-to-Video, `next_action.type` can be `check_balance` while Auto Reload is processing. Wait for [Get account details](/api-reference/account/get-account-details) to show enough credits before resubmitting. If no refill is pending, follow the reported next action when present, [buy a credit pack](https://magichour.ai/pricing?ref=docs-quickstart-402#credit-pack), or choose a request that fits your balance. * If you get `subscription_required`, [choose a subscription](https://magichour.ai/pricing?ref=docs-quickstart-402#plans). * If you get `plan_upgrade_required`, choose settings included in your current plan or [switch to a plan that supports your request](https://magichour.ai/pricing?ref=docs-quickstart-402#plans). Paid-plan models and settings require an eligible subscription. When buying credits or changing plans, sign in to the account that owns your API key. Use [Get account details](/api-reference/account/get-account-details) to confirm your balance and plan before retrying. **For persistent errors:** Contact [support@magichour.ai](mailto:support@magichour.ai) with your project ID. > [!TIP] > > 🎉 Congratulations! You have successfully created your first Magic Hour project. ## Next Steps * **Explore the API Reference:** Learn how to generate and edit videos and images programmatically. [API Reference →](/api-reference/overview) * **Explore Face Swap Video:** See parameter details, pricing, and production patterns in the [Face Swap Video guide](/tools/video/face-swap-video). * **Try All APIs in Google Colab:** [Run our complete cookbook](https://colab.research.google.com/drive/1NTHL_lr_s-qBJ-mSecSXPzRLi9_V5JiU?usp=sharing) with ready-to-run sample code. Just add your API key and start experimenting. * **Use the Web App:** Try more tools and experiment interactively at [magichour.ai](https://magichour.ai/?utm_source=docs\&utm_medium=referral\&utm_campaign=quick-start). * **Handle Results at Scale:** Set up [webhooks](https://docs.magichour.ai/integration/webhook/overview) to process results async and avoid polling. * **Join the Community:** Get help, share projects, and see what others are building in [Discord](https://discord.gg/JX5rgsZaJp). * **Stay Updated:** Check out the [Changelog](https://docs.magichour.ai/changelog) for new products and API updates. > [!TIP] > > Prefer fast iteration inside your editor? Install this documentation as an MCP server to get > contextual help while integrating the Magic Hour API. [Learn more](/integration/api-docs-mcp). # Product Video and Lip-Sync Recipes Source: https://docs.magichour.ai/get-started/starter-recipes Turn a product photo into a video, budget a catalog workflow, or sync a video to a voiceover with the Magic Hour Python SDK. These two standalone Python recipes upload local files, create one video project, wait for it to finish, and download the result. They use the official SDK's file and polling helpers instead of implementing an upload or polling loop. Prefer a browser notebook? Open one recipe in Google Colab, enter your API key through its hidden prompt, and upload your files. Each notebook creates one video. > [card] [Product Video in Colab](https://colab.research.google.com/github/magichourhq/docs/blob/main/notebooks/product-video.ipynb) > > Upload a product photo and generate a five-second clip. > [card] [Lip Sync in Colab](https://colab.research.google.com/github/magichourhq/docs/blob/main/notebooks/lip-sync.ipynb) > > Upload a video and voiceover, then preview and download the result. ## Before you start 1. Install Python 3.10 or later and create a virtual environment: ```bash theme={null} python3 -m venv .venv source .venv/bin/activate python -m pip install "magic-hour==0.78.1" ``` On Windows, activate it with `.venv\Scripts\Activate.ps1` in PowerShell. 2. [Create an API key](https://magichour.ai/developer?tab=api-keys), then set `MAGIC_HOUR_API_KEY` in your terminal environment. Keep the key out of source control, browser code, and shared notebooks. 3. Use files you own or have permission to use. For lip sync, obtain permission from the person whose likeness and voice you use. > [!WARNING] > > Each run creates a new project and uses generation credits. Check your [API pricing and credit > balance](https://magichour.ai/developer) before running. Start with one short clip, review the > output, then scale up. Interrupting the script does not cancel a submitted project. ## Choose a model for product video Start with one representative product image and compare the completed outputs, not only the generation price. Labels, logos, packaging, and geometry can change during generation, so keep a human review step before publishing a clip. | Option | Best fit | Cost or constraint for a five-second clip | | :- | :- | :- | | Account default | First integration and lowest setup friction | Uses the model and resolution available to your account | | Kling 3.0, 720p, audio off, no video reference | Camera movement from a product photo | 300 credits. Requires a paid plan. | | LTX 2.5, 480p | Lower-cost prompt iteration | 120 credits | | Seedance 2.0, 720p | Reference-driven video experiments | 1,080 credits | | Template rendering | Exact prices, legal copy, logos, and repeatable layouts | Use a deterministic renderer instead of generative motion | Model duration, resolution, audio, and plan constraints differ. Check the current [model and credit matrix](/api-reference/models) before changing the example. For a direct provider comparison, hold the model, duration, resolution, and audio settings constant and test the same product images. For a historical comparison using product-style images, see our [60-attempt video-model benchmark](https://magichour.ai/blog/ai-video-model-benchmark). It reports completed outputs and credit charges, not quality ratings or current prices. See the [source image](https://github.com/magichourhq/ai-video-model-benchmark/blob/main/assets/inputs/skincare-orbit.png) and [product output gallery](https://github.com/magichourhq/ai-video-model-benchmark/blob/main/GALLERY.md#paid-social-product-hero), which includes all attempts and failures. Those historical clips requested eight seconds at 720p, unlike the five-second recipe below. ## Product photo → five-second video For a store owner, marketer, or developer prototyping product clips: put a clear product image named `product.jpg` beside your script. A single product with an uncluttered background is a useful starting point. Save this as `product_video.py`, then run `python product_video.py` from that folder: ```python theme={null} import os from pathlib import Path from magic_hour import Client image = Path("product.jpg") if not image.is_file(): raise SystemExit("Add product.jpg beside this script before running.") client = Client(token=os.environ["MAGIC_HOUR_API_KEY"]) os.environ.setdefault("MAGIC_HOUR_POLL_INTERVAL", "3") uploaded_image = client.v1.files.upload_file(file=str(image)) job = client.v1.image_to_video.create( assets={"image_file_path": uploaded_image}, end_seconds=5, model="ltx-2.5", resolution="480p", audio=False, name="Product photo starter recipe", style={ "prompt": ( "Slow, subtle camera push-in toward the product. " "Keep the product shape, colors, packaging, and background consistent. " "Soft studio lighting. No added text or objects." ) }, ) print(f"Project ID: {job.id}", flush=True) Path("outputs/product-video").mkdir(parents=True, exist_ok=True) result = client.v1.video_projects.check_result( id=job.id, wait_for_completion=True, download_outputs=True, download_directory="outputs/product-video", ) if result.status != "complete" or not result.downloaded_paths: raise SystemExit(f"Project {result.id}: {result.status}; {result.error}") for path in result.downloaded_paths: print(f"Downloaded: {path}") ``` The script pins `ltx-2.5`, five seconds, `480p`, and no audio: 120 credits at the current 24-credit-per-second rate. These settings are available on Free and paid plans with enough credits. See the [worked funding example](/integration/evaluating-media-apis) for subscription and credit-pack USD calculations and commercial-use requirements. See [Image-to-Video](/api-reference/video-projects/image-to-video) before changing the model, duration, resolution, or audio setting. Changing those options can change cost and plan eligibility. Review the rendered clip before using it in an ad or product page. The prompt is guidance, not a guarantee that labels, logos, or product details remain exact. ### Move from one SKU to a catalog 1. Run one image through the complete recipe and verify the product remains usable. 2. Store the SKU, input-image version, prompt, model, settings, and returned project ID together. 3. Queue one project per image. Start with one active job and increase concurrency only after checking account limits and error rates. 4. Budget for successful creative attempts, including variants you reject. At 300 credits each, 100 five-second Kling 3.0 clips use 30,000 credits. Three attempts per SKU use 90,000 credits. 5. Download completed outputs to your own storage and review each clip before marking the SKU ready. The endpoint creates one project per image; it does not accept a catalog in one request. If a create request times out, use the [safe retry steps](/integration/adding-api-to-your-app#safe-retries-with-idempotency-keys) to find the original project. Before starting another batch, check `credits_charged` for every project and count any charge still reported on failed jobs. Check your [account balance](/api-reference/account/get-account-details) and leave room for frame-based charges that can still change. For a production catalog, use a durable queue, bounded concurrency, webhooks, and explicit per-item state in your database. ## Dub an existing video into another language Use [AI Video Translator](/api-reference/video-projects/ai-video-translator) when the source video already contains the speech to translate. Supply `assets.video_file_path`, `target_language` and the selected `start_seconds`/`end_seconds` interval. Read the endpoint's parameter definitions for supported languages, duration, resolution and plan constraints. Before creating the job, [estimate the credits](/api-reference/video-projects/estimate-video-credits) with the same time range and resolution. For a five-second dub at 480p, pass `tool=ai-video-translator`, `start_seconds=0`, `end_seconds=5`, and `resolution=480p`. The estimate returns `estimated_credits: 240` for those settings. Check your plan and balance before creating the project. Translation, preservation of the speaker's voice and lip synchronization are included in one job. Separate voice cloning and Lip Sync calls are unnecessary for the same dub. Retain the returned project ID, poll [video project details](/api-reference/video-projects/get-video-details) and download the completed result. Review translated meaning, voice likeness, mouth timing and the final word; these capabilities do not guarantee perfect fidelity. If replacement audio is already supplied, use the Lip Sync recipe below instead. ## Prepared image + script → spoken ad Use [AI UGC Ad Generator](/api-reference/video-projects/ai-ugc-ad-generator) with a prepared presenter/product image in `assets.image_file_path`, an approved `script` and supported `end_seconds`. This route generates video with synthesized dialogue; separate speech generation and Lip Sync calls are unnecessary for the same operation. Reuse an approved image directly and edit it only for a requested visual change or a source problem that prevents the shot. Read the endpoint's model, script, duration, resolution and plan constraints. Retain the project ID, poll for completion and review the actual product/presenter likeness, spoken claims and full sentence. For an existing recording whose performance must be preserved, use Talking Photo or Lip Sync instead of promising exact voice matching from a script-driven ad. ## Existing video + voiceover → lip-synced clip For a creator or localization workflow: put `speaker.mp4` and `voiceover.mp3` beside your script. Use a video with one clearly visible face and clean speech audio. Both inputs should cover at least the first five seconds. This recipe syncs mouth movement to **audio you already supply**; it does not translate a script, clone a voice, or generate the voiceover. For a still photo and audio, see the [Talking Photo API](/tools/video/talking-photo). Save this as `lip_sync.py`, then run `python lip_sync.py` from that folder: ```python theme={null} import os from pathlib import Path from magic_hour import Client video = Path("speaker.mp4") audio = Path("voiceover.mp3") for source in (video, audio): if not source.is_file(): raise SystemExit(f"Add {source} beside this script before running.") client = Client(token=os.environ["MAGIC_HOUR_API_KEY"]) os.environ.setdefault("MAGIC_HOUR_POLL_INTERVAL", "3") uploaded_video = client.v1.files.upload_file(file=str(video)) uploaded_audio = client.v1.files.upload_file(file=str(audio)) job = client.v1.lip_sync.create( assets={ "video_source": "file", "video_file_path": uploaded_video, "audio_file_path": uploaded_audio, }, start_seconds=0, end_seconds=5, name="Lip sync starter recipe", ) print(f"Project ID: {job.id}", flush=True) Path("outputs/lip-sync").mkdir(parents=True, exist_ok=True) result = client.v1.video_projects.check_result( id=job.id, wait_for_completion=True, download_outputs=True, download_directory="outputs/lip-sync", ) if result.status != "complete" or not result.downloaded_paths: raise SystemExit(f"Project {result.id}: {result.status}; {result.error}") for path in result.downloaded_paths: print(f"Downloaded: {path}") ``` Review lip alignment and output quality before publishing. For longer clips, adjust `end_seconds` to a range covered by your inputs; review the [Lip Sync reference](/api-reference/video-projects/lip-sync) first. ## Recover a result without generating again Both recipes print the project ID **before** waiting for the render. Save that ID. If polling or downloading fails, do not rerun the creation script just to recover the output: that would submit another billable generation. Instead, save this as `recover_video.py`, replace the ID, and run `python recover_video.py`: ```python theme={null} import os from pathlib import Path from magic_hour import Client client = Client(token=os.environ["MAGIC_HOUR_API_KEY"]) os.environ.setdefault("MAGIC_HOUR_POLL_INTERVAL", "3") Path("outputs/recovered").mkdir(parents=True, exist_ok=True) result = client.v1.video_projects.check_result( id="YOUR_EXISTING_PROJECT_ID", wait_for_completion=True, download_outputs=True, download_directory="outputs/recovered", ) if result.status != "complete" or not result.downloaded_paths: raise SystemExit(f"Project {result.id}: {result.status}; {result.error}") for path in result.downloaded_paths: print(f"Downloaded: {path}") ``` An `error` or `canceled` project will not resume rendering through this call. Inspect the returned error before deciding whether to submit a new project. If creation itself times out before returning an ID, check your dashboard before retrying; the server may have accepted the request. ## Move beyond a local prototype * Keep generation on your backend, not in a browser request with an exposed key. * Store the project ID with the user's request so interrupted work can be recovered. * The SDK polling helper waits until a terminal status; it has no overall render deadline. For production, use a background worker or [webhooks](/integration/webhook/overview), not a long-running web request. * Download or copy completed output to your storage. See [Inputs and Outputs](/integration/inputs-and-outputs) for file handling. * Keep the human quality check before turning a one-clip recipe into a batch job. # Adding API to Your App Source: https://docs.magichour.ai/integration/adding-api-to-your-app Complete guide to integrating Magic Hour APIs into your production application. This guide provides the essential concepts and patterns for integrating Magic Hour APIs into your production application. You'll learn the API workflow, project structure, and production-ready patterns. ## What you'll accomplish By the end of this guide, you'll have: * ✅ Secure API integration setup * ✅ Complete create → poll → download workflow * ✅ Robust error handling * ✅ Production-ready patterns ## Before you start > [!TIP] > > Complete the [Quick Start Guide](/get-started/quick-start) first to get familiar with basic API > calls. **Prerequisites:** * API key from [Developer Hub](https://magichour.ai/developer?tab=api-keys\&ref=docs-adding-api-to-your-app\&utm_source=docs\&utm_medium=referral\&utm_campaign=adding-api-to-your-app) * Your preferred SDK installed or direct HTTP client ready * For the Python download examples, install `requests` with `python -m pip install requests`. > [!WARNING] > > **Security:** Never expose your API key in client-side code. Always keep it secure on your server > to prevent unauthorized usage. ### Official SDK packages * [Node.js SDK on npm](https://www.npmjs.com/package/magic-hour) * [Python SDK on PyPI](https://pypi.org/project/magic_hour/) * [Go SDK on pkg.go.dev](https://pkg.go.dev/github.com/magichourhq/magic-hour-go) * [Rust SDK reference](https://docs.rs/magic_hour/latest/magic_hour/) ## Integration overview Choose the workflow that matches what you are building: * **Start with `generate()`** for quick scripts and prototypes. It creates the job, polls for completion, and can download the output for you. * **Use `create()` with webhooks or background polling** for production apps. It returns immediately so your server can track multiple jobs without holding requests open. This guide uses the production `create()` workflow. If you are still learning the API, complete the [Quick Start](/get-started/quick-start) with `generate()` first. Magic Hour APIs follow a simple 3-step pattern that applies to all content generation: ### Step 1: Create Job **Purpose:** Submit your generation request to the API **Relevant APIs:** * **Video APIs:** `POST /v1/face-swap`, `POST /v1/lip-sync`, `POST /v1/animation`, `POST /v1/text-to-video`, etc. * **Image APIs:** `POST /v1/ai-image-generator`, `POST /v1/face-swap-photo`, `POST /v1/ai-headshot-generator`, etc. * **Audio APIs:** `POST /v1/ai-voice-generator` The response contains the project `id` and `credits_charged`. Retrieve project details to check its status. ```python Python SDK theme={null} from magic_hour import Client import os client = Client(token=os.getenv("MAGIC_HOUR_API_KEY")) # 1. Create job print("Creating face swap job...") create_res = client.v1.face_swap.create( name="My face swap", assets={ "image_file_path": "https://upload.wikimedia.org/wikipedia/commons/e/ec/Chris_Cassidy_-_Official_NASA_Astronaut_Portrait_in_EMU_%28cropped%29.jpg", "video_file_path": "https://svs.gsfc.nasa.gov/vis/a010000/a014300/a014327/john_bolten_no_graphics.mp4", "video_source": "file" }, start_seconds=0.0, end_seconds=10.0, ) print(f"Job created with ID: {create_res.id}, credits: {create_res.credits_charged}") ``` ### Production application pattern **Best for:** Web apps, APIs, multiple concurrent jobs ```python theme={null} # Use create() + polling/webhooks for control create_res = client.v1.face_swap.create(...) job_id = create_res.id # Store job in database for tracking save_job_to_database(job_id, user_id, status="queued") # Use webhooks or background polling return {"job_id": job_id, "status": "processing"} ``` ## Step-by-step integration guide Let's build a complete face swap integration step by step: ### Step 1: Set up the API client **What this does:** Creates a configured Magic Hour client for making API calls ```python Python theme={null} # services/magichour.py from magic_hour import Client import os # Initialize client with environment variable client = Client(token=os.getenv("MAGIC_HOUR_API_KEY")) def get_client(): """Get configured Magic Hour client""" return client ``` ```typescript Node.js theme={null} // services/magichour.js import { Client } from "magic-hour"; // Initialize client with environment variable const client = new Client({ token: process.env.MAGIC_HOUR_API_KEY, }); export function getClient() { return client; } ``` ### Step 2: Create the job **What this does:** Submits a face swap request and gets a project ID to track progress ```python Python theme={null} # services/video_processor.py from .magichour import get_client def create_face_swap(face_image_url, video_url, start_time=0.0, end_time=10.0): """Create a face swap job and return project ID""" client = get_client() # Submit job to Magic Hour API create_res = client.v1.face_swap.create( name="Face swap job", assets={ "image_file_path": face_image_url, "video_file_path": video_url, "video_source": "file" }, start_seconds=start_time, end_seconds=end_time, ) return { "project_id": create_res.id, "credits_charged": create_res.credits_charged } ``` ```typescript Node.js theme={null} // services/videoProcessor.js import { getClient } from "./magichour.js"; export async function createFaceSwap(faceImageUrl, videoUrl, startTime = 0.0, endTime = 10.0) { const client = getClient(); // Submit job to Magic Hour API const createRes = await client.v1.faceSwap.create({ name: "Face swap job", assets: { imageFilePath: faceImageUrl, videoFilePath: videoUrl, videoSource: "file", }, startSeconds: startTime, endSeconds: endTime, }); return { projectId: createRes.id, creditsCharged: createRes.creditsCharged, }; } ``` ### Step 3: Monitor job status **What this does:** Checks if the job is complete and handles different status states ```python Python theme={null} def check_job_status(project_id): """Check the current status of a video job""" client = get_client() try: # Get current status from Magic Hour status_res = client.v1.video_projects.get(id=project_id) return { "project_id": project_id, "status": status_res.status, "downloads": status_res.downloads if status_res.status == "complete" else None, "error": status_res.error if status_res.status == "error" else None } except Exception as e: raise RuntimeError( f"Could not read project {project_id}. Check this project before submitting another job." ) from e ``` ```typescript Node.js theme={null} export async function checkJobStatus(projectId) { const client = getClient(); try { // Get current status from Magic Hour const statusRes = await client.v1.videoProjects.get({ id: projectId }); return { projectId, status: statusRes.status, downloads: statusRes.status === "complete" ? statusRes.downloads : null, error: statusRes.status === "error" ? statusRes.error : null, }; } catch (error) { throw new Error( `Could not read project ${projectId}. Check this project before submitting another job.`, { cause: error } ); } } ``` If a status request fails, the project's remote status is unknown. Keep its original ID and check it again before submitting another generation; a network failure does not mean the render failed. Use the [recovery recipe](/get-started/starter-recipes#recover-a-result-without-generating-again) to retrieve a video without creating a new job. ### Step 4: Download results **What this does:** Downloads the generated video when the job completes successfully ```python Python theme={null} # services/file_manager.py import requests import os import time from pathlib import Path def download_video(download_info, output_dir="./downloads"): """Download completed video to local storage""" # Create output directory if it doesn't exist Path(output_dir).mkdir(exist_ok=True) # Generate unique filename filename = f"face_swap_{int(time.time())}.mp4" filepath = Path(output_dir) / filename try: # Download the video file response = requests.get(download_info.url, stream=True, timeout=60) response.raise_for_status() # Save to disk with open(filepath, "wb") as file: for chunk in response.iter_content(chunk_size=8192): file.write(chunk) return { "success": True, "filepath": str(filepath), "size_bytes": filepath.stat().st_size } except Exception as e: return { "success": False, "error": str(e) } ``` ```typescript Node.js theme={null} // services/fileManager.js import fs from "fs"; import path from "path"; export async function downloadVideo(downloadInfo, outputDir = "./downloads") { // Create output directory if it doesn't exist if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }); } // Generate unique filename const filename = `face_swap_${Date.now()}.mp4`; const filepath = path.join(outputDir, filename); try { // Download the video file const response = await fetch(downloadInfo.url); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } // Save to disk const arrayBuffer = await response.arrayBuffer(); fs.writeFileSync(filepath, Buffer.from(arrayBuffer)); const stats = fs.statSync(filepath); return { success: true, filepath, sizeBytes: stats.size, }; } catch (error) { return { success: false, error: error.message, }; } } ``` ### Step 5: Put it all together **What this does:** Combines all steps into a complete workflow function These examples use the public sample media above. The first run starts a Face Swap job and uses credits. If polling or downloading stops, set `MAGIC_HOUR_PROJECT_ID` to the printed ID and rerun the example to continue that project. ```python Python theme={null} # main.py - Complete workflow from services.video_processor import create_face_swap, check_job_status from services.file_manager import download_video import os import time def process_face_swap(face_image_url, video_url, project_id=None): """Complete face swap workflow""" print("🚀 Starting face swap...") # Step 1: Create the job if not project_id: job = create_face_swap(face_image_url, video_url) project_id = job["project_id"] print(f"Credits charged: {job['credits_charged']}") print(f"Project ID: {project_id}") # Step 2: Wait for completion print("⏳ Waiting for completion...") for _ in range(60): status = check_job_status(project_id) print(f"Status: {status['status']}") if status['status'] == 'complete': if not status["downloads"]: print(f"Project {project_id} is complete. Check the same ID for a download link.") return None # Step 3: Download result result = download_video(status['downloads'][0]) if result['success']: print(f"📁 Video downloaded: {result['filepath']}") return result['filepath'] else: print(f"❌ Download failed: {result['error']}") return None elif status['status'] in ('error', 'canceled'): print(f"❌ Job failed: {status['error']}") return None time.sleep(5) # Wait 5 seconds before checking again print(f"Still waiting for project {project_id}. Set MAGIC_HOUR_PROJECT_ID to resume.") return None # Usage if __name__ == "__main__": result = process_face_swap( "https://upload.wikimedia.org/wikipedia/commons/e/ec/Chris_Cassidy_-_Official_NASA_Astronaut_Portrait_in_EMU_%28cropped%29.jpg", "https://svs.gsfc.nasa.gov/vis/a010000/a014300/a014327/john_bolten_no_graphics.mp4", project_id=os.getenv("MAGIC_HOUR_PROJECT_ID"), ) ``` ```typescript Node.js theme={null} // main.js - Complete workflow import { createFaceSwap, checkJobStatus } from "./services/videoProcessor.js"; import { downloadVideo } from "./services/fileManager.js"; export async function processFaceSwap(faceImageUrl, videoUrl, projectId) { console.log("🚀 Starting face swap..."); // Step 1: Create the job if (!projectId) { const job = await createFaceSwap(faceImageUrl, videoUrl); projectId = job.projectId; console.log(`Credits charged: ${job.creditsCharged}`); } console.log(`Project ID: ${projectId}`); // Step 2: Wait for completion console.log("⏳ Waiting for completion..."); for (let attempt = 0; attempt < 60; attempt += 1) { const status = await checkJobStatus(projectId); console.log(`Status: ${status.status}`); if (status.status === "complete") { if (!status.downloads?.length) { console.log(`Project ${projectId} is complete. Check the same ID for a download link.`); return null; } // Step 3: Download result const result = await downloadVideo(status.downloads[0]); if (result.success) { console.log(`📁 Video downloaded: ${result.filepath}`); return result.filepath; } else { console.log(`❌ Download failed: ${result.error}`); return null; } } else if (status.status === "error" || status.status === "canceled") { console.log(`❌ Job failed: ${status.error}`); return null; } await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5 seconds } console.log(`Still waiting for project ${projectId}. Set MAGIC_HOUR_PROJECT_ID to resume.`); return null; } // Usage processFaceSwap( "https://upload.wikimedia.org/wikipedia/commons/e/ec/Chris_Cassidy_-_Official_NASA_Astronaut_Portrait_in_EMU_%28cropped%29.jpg", "https://svs.gsfc.nasa.gov/vis/a010000/a014300/a014327/john_bolten_no_graphics.mp4", process.env.MAGIC_HOUR_PROJECT_ID ).then((result) => { console.log("Final result:", result); }); ``` ## Working with input files Magic Hour accepts input files in two ways: ### Option 1: URL references (Recommended) The simplest approach is to pass file URLs: ```json theme={null} { "assets": { "image_file_path": "https://upload.wikimedia.org/wikipedia/commons/e/ec/Chris_Cassidy_-_Official_NASA_Astronaut_Portrait_in_EMU_%28cropped%29.jpg", "video_file_path": "https://svs.gsfc.nasa.gov/vis/a010000/a014300/a014327/john_bolten_no_graphics.mp4" } } ``` **Supported formats:** * **Images**: PNG, JPG, JPEG, JFIF, HEIC, HEIF, WEBP, AVIF, JP2, TIFF, TIF, BMP * **Videos**: MP4, M4V, MOV, WEBM * **Audio**: MP3, WAV, AAC, FLAC, WEBM, WEBA, M4A, OPUS, OGG, OGA, AIFF, AMR See [Handling Inputs and Outputs](/integration/inputs-and-outputs#supported-file-formats) for the canonical format list and special-case support. ### Option 2: Upload to Magic Hour For secure or temporary files, upload directly to Magic Hour storage: > [card] [Inputs and Outputs Guide](/integration/inputs-and-outputs) > > Complete guide to file uploads, formats, and storage options ## Understanding job status Every job goes through these states: | Status | Description | Action Required | | :- | :- | :- | | `queued` | Job is waiting for available server | ⏳ Keep polling | | `rendering` | Job is being processed | ⏳ Keep polling | | `complete` | Job finished successfully | ✅ Download result | | `error` | Job failed during processing | ❌ Handle error | | `canceled` | Job was manually canceled | 🛑 Job stopped | Recommended polling intervals: * **Images**: Check every 2-3 seconds (usually complete within 30-60 seconds) * **Videos**: Check every 5-10 seconds (can take 2-5 minutes depending on length) ## Error handling When a job fails (`status: "error"`), the response includes detailed error information: ```json theme={null} { "status": "error", "error": { "code": "no_source_face", "message": "Please use an image with a detectable face" } } ``` ### Error handling example ```python Python SDK theme={null} try: create_res = client.v1.face_swap.create(...) # Poll with error handling while True: status_res = client.v1.video_projects.get(id=create_res.id) if status_res.status == "complete": # Success - download result break elif status_res.status in ("error", "canceled"): error_code = getattr(status_res.error, "code", "unknown") error_msg = getattr(status_res.error, "message", "Unknown error") # Handle specific errors if error_code == "no_source_face": print("❌ No face detected. Please use a different image.") else: print(f"❌ Error ({error_code}): {error_msg}") break time.sleep(5) except Exception as e: print(f"❌ Request failed: {e}") ``` ```typescript Node SDK theme={null} try { const createRes = await client.v1.faceSwap.create({...}); // Poll with error handling while (true) { const statusRes = await client.v1.videoProjects.get({ id: createRes.id }); if (statusRes.status === "complete") { // Success - download result break; } else if (statusRes.status === "error" || statusRes.status === "canceled") { const errorCode = statusRes.error?.code || "unknown"; const errorMsg = statusRes.error?.message || "Unknown error"; // Handle specific errors switch (errorCode) { case "no_source_face": console.log("❌ No face detected. Please use a different image."); break; default: console.log(`❌ Error (${errorCode}): ${errorMsg}`); } break; } await new Promise(resolve => setTimeout(resolve, 5000)); } } catch (error) { console.log(`❌ Request failed: ${error}`); } ``` > [!NOTE] > > For `unknown_error` codes, contact [support@magichour.ai](mailto:support@magichour.ai) with your > project ID for investigation. ### Safe retries with idempotency keys Project create endpoints accept an `Idempotency-Key` header, so you can safely retry a request after a timeout or connection error. Repeating a key within 24 hours returns the original project instead of creating and charging for a new one. Keys are shared across all video, image, and audio endpoints on your account. A key reused for a different project can return the earlier project. Generate and save a unique key before the first submission. Keep it with the original request so a retry sends the same key and request. The examples read that saved key from `MAGIC_HOUR_REQUEST_ID`. Set it to a fresh UUID for each new project. Keep its original value when retrying the same project. If 24 hours have passed, check your [library](https://magichour.ai/my-library) for the original project before submitting again. ```bash cURL theme={null} curl --request POST \ --url https://api.magichour.ai/v1/ai-image-generator \ --header 'authorization: Bearer ' \ --header 'content-type: application/json' \ --header "Idempotency-Key: ${MAGIC_HOUR_REQUEST_ID:?Set it to the saved key for this project}" \ --data '{"image_count": 1, "style": {"prompt": "Cool image"}}' ``` ```python Python SDK theme={null} import os request_id = os.environ.get("MAGIC_HOUR_REQUEST_ID") if not request_id: raise ValueError("Set MAGIC_HOUR_REQUEST_ID to the saved key for this project") client.v1.ai_image_generator.create( image_count=1, style={"prompt": "Cool image"}, request_options={"additional_headers": {"Idempotency-Key": request_id}}, ) ``` ```typescript Node.js SDK theme={null} const requestId = process.env.MAGIC_HOUR_REQUEST_ID; if (!requestId) throw new Error("Set MAGIC_HOUR_REQUEST_ID to the saved key for this project"); await client.v1.aiImageGenerator.create( { imageCount: 1, style: { prompt: "Cool image" } }, { additionalHeaders: { "Idempotency-Key": requestId } }, ); ``` ```go Go SDK theme={null} // Requires the fmt, net/http, and os packages. res, err := client.V1.AiImageGenerator.Create( ai_image_generator.CreateRequest{ ImageCount: 1, Style: types.V1AiImageGeneratorCreateBodyStyle{Prompt: "Cool image"}, }, func(req *http.Request) error { requestID := os.Getenv("MAGIC_HOUR_REQUEST_ID") if requestID == "" { return fmt.Errorf("set MAGIC_HOUR_REQUEST_ID to the saved key for this project") } req.Header.Set("Idempotency-Key", requestID) return nil }, ) ``` The Python and Node.js SDKs also accept the header in `generate()`: ```python Python SDK theme={null} import os request_id = os.environ.get("MAGIC_HOUR_REQUEST_ID") if not request_id: raise ValueError("Set MAGIC_HOUR_REQUEST_ID to the saved key for this project") client.v1.ai_image_generator.generate( image_count=1, style={"prompt": "Cool image"}, request_options={"additional_headers": {"Idempotency-Key": request_id}}, ) ``` ```typescript Node.js SDK theme={null} const requestId = process.env.MAGIC_HOUR_REQUEST_ID; if (!requestId) throw new Error("Set MAGIC_HOUR_REQUEST_ID to the saved key for this project"); await client.v1.aiImageGenerator.generate( { imageCount: 1, style: { prompt: "Cool image" } }, { additionalHeaders: { "Idempotency-Key": requestId } }, ); ``` The Rust SDK can't send custom headers yet. ## Status monitoring strategies Choose the right approach based on your application's needs: ### Option 1: Webhooks (Recommended for production) Get real-time notifications when jobs complete. Best for: * ✅ Production applications * ✅ Video processing (longer render times) * ✅ Multiple concurrent jobs * ✅ Better server resource usage > [card] [Webhook Setup Guide](/integration/webhook/overview) > > Complete webhook implementation guide with examples ### Option 2: Polling (Good for simple use cases) Periodically check job status. Best for: * ✅ Simple integrations * ✅ Single job processing * ✅ Image generation (quick results) **Smart polling example:** ```python Python SDK theme={null} import time def wait_for_completion(client, project_id, project_type="video", timeout_seconds=1800): """Poll with exponential backoff (3s -> 30s max) and a hard timeout.""" get_method = (client.v1.video_projects.get if project_type == "video" else client.v1.image_projects.get) deadline = time.monotonic() + timeout_seconds delay = 3.0 while time.monotonic() < deadline: res = get_method(id=project_id) print(f"Status: {res.status}") if res.status == "complete": return res # Success! if res.status in ("error", "canceled"): raise RuntimeError(f"Job {res.status}: {res.error}") time.sleep(delay) delay = min(delay * 1.5, 30.0) # back off up to 30s between checks raise TimeoutError(f"Job did not complete within {timeout_seconds}s") ``` ```typescript Node SDK theme={null} async function waitForCompletion( client: Client, projectId: string, projectType: "video" | "image" = "video", timeoutMs = 30 * 60 * 1000 ) { const deadline = Date.now() + timeoutMs; let delay = 3000; while (Date.now() < deadline) { const res = projectType === "video" ? await client.v1.videoProjects.get({ id: projectId }) : await client.v1.imageProjects.get({ id: projectId }); console.log(`Status: ${res.status}`); if (res.status === "complete") { return res; // Success! } if (res.status === "error" || res.status === "canceled") { throw new Error(`Job ${res.status}: ${JSON.stringify(res.error)}`); } await new Promise((resolve) => setTimeout(resolve, delay)); delay = Math.min(delay * 1.5, 30_000); // back off up to 30s between checks } throw new Error(`Job did not complete within ${timeoutMs}ms`); } ``` ## Downloading results When a job completes, the `downloads` array is populated with secure, time-limited URLs: ```json theme={null} { "status": "complete", "downloads": [ { "url": "https://videos.magichour.ai/id/output.mp4?auth-token=1234", "expires_at": "2024-10-19T05:16:19.027Z" } ] } ``` > [!WARNING] > > Save each file before its download URL's `expires_at`. If the URL expires, [retrieve the same > completed project for a current URL](/integration/inputs-and-outputs#getting-fresh-download-urls). ### Download outputs ```python Python SDK theme={null} import requests import os import time from pathlib import Path def download_result(download_info, output_dir="./downloads"): # Create output directory Path(output_dir).mkdir(exist_ok=True) # Generate filename from URL or use timestamp url = download_info.url filename = f"result_{int(time.time())}.mp4" # or extract from URL filepath = Path(output_dir) / filename try: print(f"Downloading to {filepath}...") response = requests.get(url, stream=True, timeout=60) response.raise_for_status() # Stream download for large files with open(filepath, "wb") as file: for chunk in response.iter_content(chunk_size=8192): file.write(chunk) print(f"✅ Downloaded: {filepath} ({filepath.stat().st_size} bytes)") return str(filepath) except requests.exceptions.RequestException as e: print(f"❌ Download failed: {e}") return None ``` ```typescript Node SDK theme={null} import fs from "fs"; import path from "path"; async function downloadResult(downloadInfo: any, outputDir = "./downloads") { // Create output directory if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }); } // Generate filename const filename = `result_${Date.now()}.mp4`; const filepath = path.join(outputDir, filename); try { console.log(`Downloading to ${filepath}...`); const response = await fetch(downloadInfo.url); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } // Stream download for large files const arrayBuffer = await response.arrayBuffer(); fs.writeFileSync(filepath, Buffer.from(arrayBuffer)); const stats = fs.statSync(filepath); console.log(`✅ Downloaded: ${filepath} (${stats.size} bytes)`); return filepath; } catch (error) { console.log(`❌ Download failed: ${error}`); return null; } } ``` ### Multiple outputs handling Some tools generate multiple files (e.g., multiple images): ```python Python SDK theme={null} # Handle multiple downloads for i, download in enumerate(status_res.downloads): filename = f"output_{i+1}.{'mp4' if 'video' in download.url else 'jpg'}" download_result(download, filename) ``` ```typescript Node SDK theme={null} for (const [i, download] of statusRes.downloads.entries()) { const filename = `output_${i + 1}.${download.url.includes("video") ? "mp4" : "jpg"}`; downloadResult(download, filename); } ``` ## File management ### Cleaning up storage Generated files are stored indefinitely. Clean up completed jobs to manage storage: ```python Python SDK theme={null} client.v1.video_projects.delete(id="cuid") ``` ```typescript Node SDK theme={null} await client.v1.videoProjects.delete({ id: "cuid" }); ``` > [!WARNING] > > Deletion is permanent and cannot be undone. Only delete after confirming successful download. ## Development and testing ### Free testing with mock server Avoid credit charges during development by using the mock API server: > [!NOTE] > > The mock server returns realistic sample data without processing jobs or charging credits. ```python Python SDK theme={null} from magic_hour import Client from magic_hour.environment import Environment # Use mock server for development client = Client( token="YOUR_API_KEY", # Can use any value for mock mode environment=Environment.MOCK_SERVER ) # All API calls will return mock data result = client.v1.face_swap.create(...) # No credits charged ``` ```typescript Node SDK theme={null} import { Client, Environment } from "magic-hour"; // Use mock server for development const client = new Client({ token: "YOUR_API_KEY", // Can use any value for mock mode environment: Environment.MockServer, }); // All API calls will return mock data const result = await client.v1.faceSwap.create({...}); // No credits charged ``` ### Job cancellation Cancel video jobs (with full refund) via the web dashboard: **1. Open project details** Visit the project in your library: - **Videos**: `https://magichour.ai/my-library?videoId= {project_id}` - **Images**: `https://magichour.ai/my-library?imageId={project_id}` - **Audio**: `https://magichour.ai/my-library?audioId={project_id}` **2. Click cancel render** ![Cancel Render Button](https://mintcdn.com/magichour/M34pwKnkDTQb_OER/integration/images/cancel-1.jpg?fit=max\&auto=format\&n=M34pwKnkDTQb_OER\&q=85\&s=451d6a29f363eb2beb64b2d2b6fa3cac) **3. Confirm cancellation** ![Confirm Cancel Button](https://mintcdn.com/magichour/M34pwKnkDTQb_OER/integration/images/cancel-2.jpg?fit=max\&auto=format\&n=M34pwKnkDTQb_OER\&q=85\&s=421403adcc133f369cd980b5f7442752) **4. Cancellation complete** ![Cancel Success](https://mintcdn.com/magichour/M34pwKnkDTQb_OER/integration/images/cancel-3.jpg?fit=max\&auto=format\&n=M34pwKnkDTQb_OER\&q=85\&s=76e1fe438889b8d68cd5e6bd3b21482c) Notes: * In the web dashboard, queued image jobs using self-hosted/open-source models can be canceled while still pending. Image jobs that have started rendering, or use third-party models, cannot be canceled. * API-based cancellation is not currently available * Full credit refund is provided for cancelled video jobs ## Next steps > [card] [Webhook Integration](/integration/webhook/overview) > > Set up real-time notifications for production apps > [card] [API Reference](/api-reference) > > Explore all available endpoints and parameters > [card] [Google Colab Cookbook](https://colab.research.google.com/drive/1NTHL_lr_s-qBJ-mSecSXPzRLi9_V5JiU?usp=sharing) > > Try the Magic Hour APIs with ready-to-run examples > [card] [File Management](/integration/inputs-and-outputs) > > Advanced file upload and management techniques *** **Need help?** Join our [Discord community](https://discord.com/invite/JX5rgsZaJp) or email [support@magichour.ai](mailto:support@magichour.ai) # Adobe Express add-on Source: https://docs.magichour.ai/integration/adobe-express Animate an image or an explicitly exported page with Magic Hour and add the result to Adobe Express. The stable development add-on accepts an uploaded image or an explicit current-page export, generates a short video, and adds the completed MP4 to Adobe Express after preview. Restricted exports are refused. > [!WARNING] > > Adobe's selected-element rendition API is experimental and cannot be distributed yet. A separate > development-only build captures one selected element. The stable build uses file upload or an > explicitly chosen current page, and does not silently substitute a page for a selected element. > [card] [Build and install](https://github.com/magichourhq/docs/tree/main/examples/design-video/adobe-express) > > Build the stable add-on or the isolated experimental selection build, then load it through Adobe's > development tools. The API key stays in session memory. Prompts and the chosen image go to Magic Hour; generation uses API credits. **Add video to design** imports the MP4 Blob through Adobe's native video API. The source remains unchanged. The add-on saves accepted project IDs for recovery. **Stop waiting** stops the local wait; **Resume generation** retrieves the existing project without another paid submission. Live Magic Hour generation and browser preview passed. The native API contract was tested with simulated Adobe APIs. Actual Adobe Express installation and marketplace review remain required. See the [validation record](/integration/design-video-integrations-validation). # Evaluate Lip Sync for Agency and Localization Work Source: https://docs.magichour.ai/integration/agency-lip-sync Test existing speaker footage with approved voiceovers, record quality and accepted-output cost, and prepare a repeatable client delivery workflow. For an agency localizing an existing speaker video, Magic Hour's lip-sync workflow takes a video and replacement audio. It animates mouth movement; it does not by itself validate a translation, approve a voice or finish the ad. If your starting asset is a still portrait, use [Talking Photo](/tools/video/talking-photo) instead. This is a pilot process, not a claim that Magic Hour outperforms another provider. ## Prepare one representative clip 1. Obtain permission for the footage, likeness and voice. Approve the translated script and replacement recording before generation. Check the current [terms of service](https://magichour.ai/terms-of-service): commercial use requires a paid subscription or credit-pack purchase, subject to applicable rights. 2. Start with a short, clear single-speaker segment with visible lips and stable lighting. Set the segment with `start_seconds` and `end_seconds` and provide enough audio for it. The [Lip Sync guide](/tools/video/lip-sync) lists input requirements and supported audio formats. 3. Set a small generation budget and a fixed retry allowance. Check `style.generation_mode`, `max_fps_limit` and current [pricing](/tools/video/lip-sync#pricing) before submitting. 4. Run the [lip-sync starter recipe](/get-started/starter-recipes) or use the [web workflow](https://magichour.ai/products/lip-sync) for a manual pilot. The recipe uploads local files, submits a project, waits and downloads the output. ## Review the delivered result This example uses a fictional presenter and a 2.96-second synthetic voiceover. Play the result with sound to compare the mouth movement with the silent source. **Original clip**