Quick StartExamples

Find and Use a Model or LoRA

Search the PixAI Model Market from the API, pick a LoRA that fits your base model, read its trigger words and sizes, and generate with it.

Every model and LoRA on the PixAI Model Market can be used from the API. This guide searches for a LoRA, checks that it fits the base model, and generates an image with it.

Base URL: https://api.pixai.art/v2. The model endpoints work without an API key, but send Authorization: Bearer YOUR_API_KEY to see the same models your account sees; anonymous searches are filtered more strictly. Image creation always needs the key; see How can I use PixAI API?.

Generation endpoints take version IDs. A search result's id is the model ID; pass its latestAvailableVersionId instead.

Steps

Pick a base model

Start from one of the recommended models, or search for base models with usageType=MODEL. Read the version to learn its type, which a LoRA has to match:

curl https://api.pixai.art/v2/generation-model-version/1861558740588989558
{
  "id": "1861558740588989558",
  "modelId": "1861558737426484240",
  "modelTitle": "Haruka v2",
  "modelType": "SDXL_MODEL",
  "status": "available"
}

Haruka v2 is an SDXL_MODEL, so it takes SDXL LoRAs.

Search for a LoRA

Search with usageType=LORA, a keyword, and the base model's type in loraBaseModelTypes:

curl "https://api.pixai.art/v2/generation-model/search?usageType=LORA&keyword=watercolor&loraBaseModelTypes=SDXL_MODEL&size=5" \
  -H "Authorization: Bearer $PIXAI_API_KEY"

Each item in data is a model. The fields you need:

{
  "id": "1682965664660673855",
  "title": "Anime Watercolor style XL",
  "type": "MULTI_LORA",
  "loraBaseModelTypes": ["SDXL_MODEL"],
  "permittedUse": "PERSONAL",
  "latestAvailableVersionId": "1682965664694228288",
  "latestAvailableVersion": {
    "id": "1682965664694228288",
    "loraBaseModelType": "SDXL_MODEL",
    "extra": { "triggerWords": "watercolor (medium), (watercolor)" }
  }
}

Results rank by relevance and popularity. Page with offset and size while hasMore is true, and add permittedUse=COMMERCIAL if you need a license that allows commercial use.

Check that the version fits

loraBaseModelTypes covers all of a LoRA's versions, and the latest one may be for a different base model. Check that latestAvailableVersion.loraBaseModelType is your base model's type. If it is not, list the model's versions for your type, newest first, and take the first id:

curl "https://api.pixai.art/v2/generation-model/1682965664660673855/versions?baseModelType=SDXL_MODEL"

Its trigger words are in extra.triggerWords. The API adds them to the prompt for you unless you send your own in triggerWords.

Choose a size

aspectRatio and size work on every model. For an exact width and height, read the sizes the base model accepts:

curl https://api.pixai.art/v2/generation-model/1861558740588989558/size-config

Each entry of ranges gives minWidth–maxWidth, minHeight–maxHeight and a step that both sides must be a multiple of, plus ready-made presets. Entries with accessStatus: "membership_required" need a higher membership tier.

Generate with the LoRA

Pass the LoRA's version ID in loras[].modelId, with a weight from 0 to 1:

curl -X POST https://api.pixai.art/v2/image/create \
  -H "Authorization: Bearer $PIXAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "modelVersionId": "1861558740588989558",
    "prompt": "1girl, solo, straw hat, sunflower field, summer, blue sky",
    "aspectRatio": "2:3",
    "loras": [
      { "modelId": "1682965664694228288", "weight": 0.8 }
    ]
  }'

Then poll GET /v2/task/{id} and download the result, as in Your First API Call.

You can combine up to 3 LoRAs without a membership, and up to 15 with one; more answers 403 LORA_NUM_EXCEEDED. A higher weight makes a LoRA's effect stronger.

Full script

Search for a LoRA that fits Haruka v2, then generate with it. Set PIXAI_API_KEY in your environment first.

With requests installed:

import os
import time

import requests

API = "https://api.pixai.art/v2"
HEADERS = {"Authorization": f"Bearer {os.environ['PIXAI_API_KEY']}"}
BASE_VERSION = "1861558740588989558"  # Haruka v2


def get(path, **params):
    resp = requests.get(f"{API}{path}", headers=HEADERS, params=params)
    resp.raise_for_status()
    return resp.json()


base = get(f"/generation-model-version/{BASE_VERSION}")
base_type = base["modelType"]

results = get(
    "/generation-model/search",
    usageType="LORA",
    keyword="watercolor",
    loraBaseModelTypes=base_type,
    size=10,
)["data"]

lora = None
for model in results:
    latest = model.get("latestAvailableVersion") or {}
    if latest.get("loraBaseModelType") == base_type:
        lora = latest
        break
if lora is None:
    raise SystemExit(f"No LoRA for {base_type} in the first page of results")
print("Using", lora["modelTitle"], lora["id"], "trigger words:", lora["extra"].get("triggerWords"))

resp = requests.post(
    f"{API}/image/create",
    headers=HEADERS,
    json={
        "modelVersionId": BASE_VERSION,
        "prompt": "1girl, solo, straw hat, sunflower field, summer, blue sky",
        "aspectRatio": "2:3",
        "loras": [{"modelId": lora["id"], "weight": 0.8}],
    },
)
resp.raise_for_status()
task = resp.json()

while task["status"] in ("waiting", "running"):
    time.sleep(2)
    resp = requests.get(f"{API}/task/{task['id']}", headers=HEADERS)
    if resp.status_code == 404:  # A new task can answer 404 for a moment. Keep polling.
        continue
    resp.raise_for_status()
    task = resp.json()

if task["status"] != "completed":
    raise SystemExit(f"Task ended as {task['status']}: {task.get('taskStatusMsgI18n')}")

with open("lora.webp", "wb") as f:
    f.write(requests.get(task["outputs"]["mediaUrls"][0]).content)

For Node.js 20 or later, saved as lora.mjs:

import { writeFile } from 'node:fs/promises';

const API = 'https://api.pixai.art/v2';
const HEADERS = {
  Authorization: `Bearer ${process.env.PIXAI_API_KEY}`,
  'Content-Type': 'application/json',
};
const BASE_VERSION = '1861558740588989558'; // Haruka v2

async function call(path, init = {}) {
  const res = await fetch(`${API}${path}`, { headers: HEADERS, ...init });
  if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`);
  return res.json();
}

// A task can answer 404 for a moment right after it is created: keep polling.
async function poll(taskId) {
  const res = await fetch(`${API}/task/${taskId}`, { headers: HEADERS });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`/task/${taskId}: ${res.status} ${await res.text()}`);
  return res.json();
}

const base = await call(`/generation-model-version/${BASE_VERSION}`);
const query = new URLSearchParams({
  usageType: 'LORA',
  keyword: 'watercolor',
  loraBaseModelTypes: base.modelType,
  size: '10',
});
const { data } = await call(`/generation-model/search?${query}`);
const lora = data
  .map((model) => model.latestAvailableVersion)
  .find((version) => version?.loraBaseModelType === base.modelType);
if (!lora) throw new Error(`No LoRA for ${base.modelType} in the first page of results`);
console.log('Using', lora.modelTitle, lora.id, 'trigger words:', lora.extra?.triggerWords);

let task = await call('/image/create', {
  method: 'POST',
  body: JSON.stringify({
    modelVersionId: BASE_VERSION,
    prompt: '1girl, solo, straw hat, sunflower field, summer, blue sky',
    aspectRatio: '2:3',
    loras: [{ modelId: lora.id, weight: 0.8 }],
  }),
});
while (task.status === 'waiting' || task.status === 'running') {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  task = (await poll(task.id)) ?? task;
}
if (task.status !== 'completed') {
  throw new Error(`Task ended as ${task.status}: ${JSON.stringify(task.taskStatusMsgI18n)}`);
}

const image = await fetch(task.outputs.mediaUrls[0]);
await writeFile('lora.webp', Buffer.from(await image.arrayBuffer()));

Reference