Call an image generation API from Python

5 min read · Magnt Editorial · September 8, 2026

You do not need an SDK to make your first Magnt image request. Python’s standard library can send the JSON body, read the response and save a WebP file. The important parts are keeping the key private and handling failed requests before writing output.

Prepare the account and the environment

Create an API key in the Magnt developer playground and set MAGNT_API_KEY in the environment where the script runs. The key identifies the Magnt account whose plan allowance or credits will be consumed. It should not be pasted into the source file or printed with debug output.

This is a server or local-script example, not code to embed in a public client. If Python powers your web backend, authenticate the user of your app before letting their request consume your Magnt allowance. A key alone is not a per-customer budget system.

Generate and save the image

Save the example as generate.py. It uses json, os, pathlib and urllib from the Python standard library. The JSON payload is encoded as UTF-8 for the request, while the successful response is written as bytes to image.webp.

The Content-Type check helps prevent an unexpected response from being saved under an image filename. HTTP failures are read as JSON errors and reported with their status. Keep the returned message separate from the API key when recording an error in your own application.

import json
import os
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError

payload = {
    "model": "magnt-image-1",
    "prompt": "A ceramic vase beside a sunlit window",
    "aspect_ratio": "4:5",
    "resolution": "1K",
    "response_format": "image",
}
request = Request(
    "https://magnt.app/api/v1/images/generations",
    data=json.dumps(payload).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + os.environ["MAGNT_API_KEY"],
        "Content-Type": "application/json",
    },
    method="POST",
)
try:
    with urlopen(request, timeout=240) as response:
        if response.headers.get_content_type() != "image/webp":
            raise RuntimeError("Unexpected response type")
        Path("image.webp").write_bytes(response.read())
except HTTPError as error:
    details = json.loads(error.read())
    raise RuntimeError(
        f"Magnt {error.code}: {details['error']['message']}"
    ) from None

Choose a composition for the destination

The example requests a 4:5 portrait canvas. Magnt also supports 1:1, 3:2, 2:3, 16:9 and 9:16, with 1K or 2K resolution. Choose the ratio for the place the image will appear rather than generating a square image and assuming every crop will work.

For a wide article image, ask for a landscape composition with deliberate empty space where the title belongs. For a product card, centre the item and review it at card size. Image settings control the requested composition; your application should still inspect the returned image before publishing it.

Add another request deliberately

This script makes one request and writes one output. There is no batch operation hidden in the endpoint, and the current account rate limit is 30 generation requests per hour. A production batch tool needs its own queue and user-visible progress instead of a tight loop that ignores failures.

A timeout stops waiting at the client, but the generation may still finish. Do not automatically retry an uncertain request. Handle an explicit 401 by fixing the key, a 402 by checking allowance, and a 429 by slowing down. Failed generation restores the reservation when Magnt handles the failure; abrupt process termination is a separate limitation.

Keep only the outputs your application needs

Magnt does not host a permanent URL for this result or retain a generation history. The local image.webp file exists because this script saves it. A web application can instead forward the bytes to a browser and let the user choose Download.

If you are building an editing workflow, the same endpoint accepts inline images in the request. Encode the source bytes with the correct MIME prefix and check the full JSON size before sending it.

Bring image generation into your app.

Create a Magnt API key, test a prompt and receive the image directly. Your existing plan allowance or credits apply.

Create an API key →

Keep reading