इसे छोड़कर कंटेंट पर जाएं
Invoke

Multi-User API गाइड

यह guide बताती है कि single-user और multi-user, दोनों modes में InvokeAI की API के साथ कैसे interact करें। API का व्यवहार multiuser configuration सेटिंग पर निर्भर करता है।

Single-User Mode (multiuser: false; deprecated):

  • Project, जनरेशन और gallery requests बिना token के internal system account इस्तेमाल करती हैं।
  • Server को सिर्फ़ अपने computer पर उपलब्ध रखें, क्योंकि जो भी उस तक पहुँच सकता है उसके पास administrator privileges होते हैं।

Multi-User Mode (multiuser: true या option मौजूद न हो, जो default है):

  • JWT token authentication ज़रूरी
  • Resources तक user-scoped access
  • Role-based authorization (admin बनाम सामान्य user)
  • Users के बीच data isolation

Authentication (सिर्फ़ Multi-User Mode)

Section titled “Authentication (सिर्फ़ Multi-User Mode)”

प्रमाणीकरण की प्रक्रिया

Section titled “प्रमाणीकरण की प्रक्रिया”

जब multi-user mode enabled होता है, तो ज़्यादातर API endpoints को JWT bearer tokens से authentication की ज़रूरत होती है। बिना authentication वाले authentication endpoints GET /api/v1/auth/status, POST /api/v1/auth/setup और POST /api/v1/auth/login हैं।

Authentication प्रक्रिया:

  1. Token प्राप्त करें: Credentials को /api/v1/auth/login पर POST करें
  2. Token स्टोर करें: JWT token को सुरक्षित रूप से सेव करें
  3. Token इस्तेमाल करें: सभी requests के लिए Authorization header में token शामिल करें
  4. Refresh: Token expire होने पर फिर से authenticate करें

Endpoint: POST /api/v1/auth/login

Request:

{
"email": "[email protected]",
"password": "SecurePassword123",
"remember_me": false
}

Response (सफल):

{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"user_id": "abc123",
"email": "[email protected]",
"display_name": "John Doe",
"is_admin": false,
"is_active": true,
"created_at": "2024-01-15T10:00:00Z",
"updated_at": "2024-01-15T10:00:00Z",
"last_login_at": "2024-01-15T15:30:00Z"
},
"expires_in": 86400
}

Response (Error):

{
"detail": "Incorrect email or password"
}

Status codes:

  • 200 OK — Authentication सफल
  • 401 Unauthorized — अमान्य credentials
  • 403 Forbidden — Account disabled है
  • 422 Unprocessable Entity — अमान्य request format

Token इस्तेमाल करना

Section titled “Token इस्तेमाल करना”

JWT token को Bearer scheme के साथ Authorization header में शामिल करें:

HTTP Header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

HTTP Request का उदाहरण:

GET /api/v1/boards HTTP/1.1
Host: localhost:9090
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json

Tokens की एक सीमित अवधि होती है:

  • Default: 24 घंटे (86400 seconds)
  • Remember Me: 7 दिन (604800 seconds)

Expiration संभालना:

import requests
import time
def api_request(url, token, max_retries=1):
headers = {"Authorization": f"Bearer {token}"}
response = requests.get(url, headers=headers)
if response.status_code == 401: # Token expired
# Re-authenticate and retry
new_token = login()
headers = {"Authorization": f"Bearer {new_token}"}
response = requests.get(url, headers=headers)
return response

Endpoint: POST /api/v1/auth/logout

Request:

POST /api/v1/auth/logout HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Response:

{
"success": true
}

Note: JWT tokens के साथ, logout मुख्य रूप से client-side होता है (token डिलीट करें)। Server-side session invalidation भविष्य की releases में जोड़ा जा सकता है।

requests library इस्तेमाल करते हुए:

import requests
import json
class InvokeAIClient:
def __init__(self, base_url="http://localhost:9090"):
self.base_url = base_url
self.token = None
def login(self, email, password, remember_me=False):
"""Authenticate and store token."""
url = f"{self.base_url}/api/v1/auth/login"
payload = {
"email": email,
"password": password,
"remember_me": remember_me
}
response = requests.post(url, json=payload)
response.raise_for_status()
data = response.json()
self.token = data["token"]
return data["user"]
def _get_headers(self):
"""Get headers with authentication token."""
if not self.token:
raise Exception("Not authenticated. Call login() first.")
return {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json"
}
def get_boards(self):
"""Get user's boards."""
url = f"{self.base_url}/api/v1/boards/"
response = requests.get(url, headers=self._get_headers())
response.raise_for_status()
return response.json()
def create_board(self, board_name):
"""Create a new board."""
url = f"{self.base_url}/api/v1/boards/"
response = requests.post(
url,
params={"board_name": board_name},
headers=self._get_headers()
)
response.raise_for_status()
return response.json()
def logout(self):
"""Logout and clear token."""
url = f"{self.base_url}/api/v1/auth/logout"
response = requests.post(url, headers=self._get_headers())
self.token = None
return response.json()
# Usage
client = InvokeAIClient()
user = client.login("[email protected]", "SecurePassword123")
print(f"Logged in as: {user['display_name']}")
boards = client.get_boards()
print(f"User has {len(boards['items'])} boards")
new_board = client.create_board("My New Board")
print(f"Created board: {new_board['board_name']}")
client.logout()

Error handling:

import requests
from requests.exceptions import HTTPError
def safe_api_call(client, method, *args, **kwargs):
"""Make API call with error handling."""
try:
func = getattr(client, method)
return func(*args, **kwargs)
except HTTPError as e:
if e.response.status_code == 401:
print("Authentication failed or token expired")
# Re-authenticate
client.login(email, password)
# Retry
return func(*args, **kwargs)
elif e.response.status_code == 403:
print("Permission denied")
elif e.response.status_code == 404:
print("Resource not found")
else:
print(f"API error: {e.response.status_code}")
print(e.response.text)
raise
# Usage
try:
boards = safe_api_call(client, "get_boards")
except Exception as e:
print(f"Failed to get boards: {e}")

fetch API इस्तेमाल करते हुए:

class InvokeAIClient {
constructor(baseUrl = 'http://localhost:9090') {
this.baseUrl = baseUrl;
this.token = null;
}
async login(email, password, rememberMe = false) {
const response = await fetch(`${this.baseUrl}/api/v1/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email,
password,
remember_me: rememberMe,
}),
});
if (!response.ok) {
throw new Error(`Login failed: ${response.statusText}`);
}
const data = await response.json();
this.token = data.token;
// Store token in localStorage
localStorage.setItem('invokeai_token', data.token);
return data.user;
}
getHeaders() {
if (!this.token) {
throw new Error('Not authenticated. Call login() first.');
}
return {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
};
}
async getBoards() {
const response = await fetch(`${this.baseUrl}/api/v1/boards/`, {
headers: this.getHeaders(),
});
if (!response.ok) {
throw new Error(`Failed to get boards: ${response.statusText}`);
}
return response.json();
}
async createBoard(boardName) {
const url = new URL(`${this.baseUrl}/api/v1/boards/`);
url.searchParams.set('board_name', boardName);
const response = await fetch(url, {
method: 'POST',
headers: this.getHeaders(),
});
if (!response.ok) {
throw new Error(`Failed to create board: ${response.statusText}`);
}
return response.json();
}
async logout() {
const response = await fetch(`${this.baseUrl}/api/v1/auth/logout`, {
method: 'POST',
headers: this.getHeaders(),
});
this.token = null;
localStorage.removeItem('invokeai_token');
return response.json();
}
}
// Usage
(async () => {
const client = new InvokeAIClient();
try {
const user = await client.login('[email protected]', 'SecurePassword123');
console.log(`Logged in as: ${user.display_name}`);
const boards = await client.getBoards();
console.log(`User has ${boards.items.length} boards`);
const newBoard = await client.createBoard('My New Board');
console.log(`Created board: ${newBoard.board_name}`);
await client.logout();
} catch (error) {
console.error('Error:', error.message);
}
})();

Types के साथ TypeScript:

interface LoginRequest {
email: string;
password: string;
remember_me?: boolean;
}
interface User {
user_id: string;
email: string;
display_name: string;
is_admin: boolean;
is_active: boolean;
created_at: string;
}
interface LoginResponse {
token: string;
user: User;
expires_in: number;
}
interface Board {
board_id: string;
board_name: string;
created_at: string;
updated_at: string;
deleted_at?: string;
cover_image_name?: string;
}
class InvokeAIClient {
private baseUrl: string;
private token: string | null = null;
constructor(baseUrl: string = 'http://localhost:9090') {
this.baseUrl = baseUrl;
}
async login(
email: string,
password: string,
rememberMe: boolean = false
): Promise<User> {
const response = await fetch(`${this.baseUrl}/api/v1/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, remember_me: rememberMe }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Login failed');
}
const data: LoginResponse = await response.json();
this.token = data.token;
return data.user;
}
private getHeaders(): HeadersInit {
if (!this.token) {
throw new Error('Not authenticated');
}
return {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
};
}
async getBoards(): Promise<{ items: Board[] }> {
const response = await fetch(`${this.baseUrl}/api/v1/boards/`, {
headers: this.getHeaders(),
});
if (!response.ok) {
throw new Error('Failed to get boards');
}
return response.json();
}
}

Login:

टर्मिनल विंडो
# Login and extract token
TOKEN=$(curl -X POST http://localhost:9090/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "SecurePassword123",
"remember_me": false
}' | jq -r '.token')
echo "Token: $TOKEN"

Boards प्राप्त करें:

टर्मिनल विंडो
curl -X GET http://localhost:9090/api/v1/boards/ \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json"

Board बनाएँ:

टर्मिनल विंडो
curl -X POST "http://localhost:9090/api/v1/boards/?board_name=My%20API%20Board" \
-H "Authorization: Bearer $TOKEN"

Multi-user mode में, clients नीचे दिए endpoints बिना token के इस्तेमाल कर सकते हैं:

  • GET /api/v1/auth/status — जाँचें कि multi-user सेटअप ज़रूरी है या नहीं
  • POST /api/v1/auth/setup — शुरुआती admin सेटअप
  • POST /api/v1/auth/login — User login
  • GET /api/v1/workflows/i/{workflow_id}/thumbnail — Workflow thumbnail

Full इमेज (GET /api/v1/images/i/{image_name}/full) और इमेज thumbnails (GET /api/v1/images/i/{image_name}/thumbnail) के लिए authentication और इमेज तक read access ज़रूरी है। API clients अपना bearer token भेज सकते हैं। Browsers login के समय सेट की गई path-scoped HttpOnly media cookie इस्तेमाल कर सकते हैं।

हर user के अपने संसाधन

Section titled “हर user के अपने संसाधन”

Resources अब authenticated user के अनुसार filter किए जाते हैं:

Boards:

# Before (single-user)
GET /api/v1/boards/?all=true # Returns all boards
# After (multi-user)
GET /api/v1/boards/?all=true # Returns boards the current user can access, including their own boards, boards they are a member of and boards with general access; admins can see all boards

Images:

# Images are filtered by board ownership
GET /api/v1/images/ # Only shows images on user's boards

Workflows:

# Returns user's workflows + public workflows
GET /api/v1/workflows/

Queue:

# Regular users see their own queue items in full and may see redacted details for other users' items on queue-status endpoints
GET /api/v1/queue/... # Queue data, sanitized for non-admin viewers
# With origin_prefix, item_ids, current, next and status cover only the caller's own items
GET /api/v1/queue/{queue_id}/status?origin_prefix=webv2:p:<project_id>:q:
# Administrators see all queue items in full
GET /api/v1/queue/... # Full queue data

कुछ endpoints को administrator privileges की ज़रूरत होती है:

User Management:

GET /api/v1/auth/users # List users (admin only)
POST /api/v1/auth/users # Create user (admin only)
GET /api/v1/auth/users/{id} # Get user (admin only)
PATCH /api/v1/auth/users/{id} # Update user (admin only)
DELETE /api/v1/auth/users/{id} # Delete user (admin only)

Model Management (write operations):

POST /api/v2/models/install # Install model (admin only)
DELETE /api/v2/models/i/{key} # Delete model (admin only)
PATCH /api/v2/models/i/{key} # Update model (admin only)
PUT /api/v2/models/convert/{key} # Convert model (admin only)

Model Management (read operations):

GET /api/v2/models/ # List models (all users)
GET /api/v2/models/i/{key} # Get model details (all users)

401 Unauthorized:

{
"detail": "Invalid authentication credentials"
}

यह तब होता है जब:

  • Token मौजूद नहीं है
  • Token invalid है
  • Token expire हो गया है
  • Token signature invalid है

403 Forbidden:

{
"detail": "Admin privileges required"
}

यह तब होता है जब:

  • User सिर्फ़-admin operation की कोशिश करता है
  • Account disabled है
  • पर्याप्त permissions नहीं हैं

404 Not Found:

{
"detail": "Resource not found"
}

यह तब होता है जब:

  • Resource मौजूद नहीं है
  • User के पास resource तक access नहीं है

प्रमाणीकरण के endpoints

Section titled “प्रमाणीकरण के endpoints”

जाँचें कि initial administrator सेटअप ज़रूरी है या नहीं

Section titled “जाँचें कि initial administrator सेटअप ज़रूरी है या नहीं”

Endpoint: GET /api/v1/auth/status

विवरण: एक SetupStatusResponse लौटाता है जो बताता है कि सेटअप की ज़रूरत है या नहीं और multiuser mode की स्थिति क्या है।

Request: कोई parameters नहीं

Response (initial सेटअप अभी पूरा नहीं हुआ):

{
"setup_required": true,
"multiuser_enabled": true,
"strict_password_checking": true,
"admin_email": null,
"has_single_user_work": true
}

Response (सेटअप पहले से पूरा है, या multiuser disabled है):

{
"setup_required": false,
"multiuser_enabled": true,
"strict_password_checking": true,
"admin_email": null,
"has_single_user_work": false
}

Administrator सेटअप करें

Section titled “Administrator सेटअप करें”

Endpoint: POST /api/v1/auth/setup

विवरण: Initial administrator account बनाएँ (सिर्फ़ तब काम करता है जब कोई admin मौजूद न हो)। नए administrator को उसी transaction में single-user mode का काम मिलता है। जब single-user mode का कोई job चल रहा हो, तो सिर्फ़ सहेजी गई interface state जाती है; बाकी transfer का इंतज़ार करता है।

Request:

{
"email": "[email protected]",
"display_name": "Administrator",
"password": "SecureAdminPass123"
}

Response:

{
"success": true,
"user": {
"user_id": "abc123",
"email": "[email protected]",
"display_name": "Administrator",
"is_admin": true,
"is_active": true
}
}

मौजूदा user प्राप्त करें

Section titled “मौजूदा user प्राप्त करें”

Endpoint: GET /api/v1/auth/me

विवरण: मौजूदा authenticated user की जानकारी प्राप्त करें

Request:

GET /api/v1/auth/me
Authorization: Bearer <token>

Response:

{
"user_id": "abc123",
"email": "[email protected]",
"display_name": "John Doe",
"is_admin": false,
"is_active": true,
"created_at": "2024-01-15T10:00:00Z",
"updated_at": "2024-01-15T10:00:00Z",
"last_login_at": "2024-01-15T15:30:00Z"
}

User management endpoints (सिर्फ़ Admin)

Section titled “User management endpoints (सिर्फ़ Admin)”

Endpoint: GET /api/v1/auth/users

Request:

GET /api/v1/auth/users
Authorization: Bearer <admin_token>

Response:

[
{
"user_id": "abc123",
"email": "[email protected]",
"display_name": "John Doe",
"is_admin": false,
"is_active": true,
"created_at": "2024-01-15T10:00:00Z",
"updated_at": "2024-04-25T17:23:00Z",
"last_login_at": "2024-01-15T15:30:00Z"
}
]

Endpoint: GET /api/v1/auth/single-user-work

विवरण: Transfer से internal system account से call करने वाले administrator के पास, प्रकार के अनुसार, क्या जाएगा। जिन rows की key administrator पहले से इस्तेमाल करता है, वे गिनी नहीं जातीं, क्योंकि transfer उन्हें वहीं छोड़ देता है।

Response:

{
"projects": 2,
"project_workspaces": 2,
"boards": 3,
"images": 120,
"videos": 0,
"workflows": 1,
"style_presets": 0,
"system_prompts": 0,
"wildcards": 3,
"fonts": 0,
"queue_items": 15
}

Endpoint: POST /api/v1/auth/single-user-work/transfer

विवरण: वह काम call करने वाले administrator के पास ले जाएँ। invoke-usermod --email <email> --return-to-single-user single-user mode पर बदलने से पहले किसी account का काम वापस system के पास ले जाता है। दोहराने पर सिर्फ़ वही जाता है जो system को उसके बाद मिला। Response बताता है कि ऊपर वाले रूप में क्या गया, और क्या system के पास रहा क्योंकि administrator उसकी key पहले से इस्तेमाल करता है: कोई wildcard नाम या किसी private font की फ़ाइल। सहेजी गई interface state system के पास रहती है।

{
"moved": {
"projects": 2,
"project_workspaces": 2,
"boards": 3,
"images": 120,
"videos": 0,
"workflows": 1,
"style_presets": 0,
"system_prompts": 0,
"wildcards": 3,
"fonts": 0,
"queue_items": 15
},
"skipped": { "wildcards": 1, "fonts": 0 }
}

दोनों endpoints को administrator का token चाहिए: बिना valid token वाली request को 401 मिलता है, और जो account administrator नहीं है उसे 403 मिलता है। सिर्फ़ multiuser mode tokens जारी करता है; server को single-user mode पर बदलने से पहले जारी किए गए token को 403 मिलता है। जब system का कोई job चल रहा हो (job पूरा होने पर फिर से कोशिश करें) या अगर administrator ने इस बीच कोई conflicting row बदली हो, तो transfer 409 लौटाता है और कुछ नहीं ले जाता।

Endpoint: POST /api/v1/auth/users

Request:

{
"email": "[email protected]",
"display_name": "New User",
"password": "TempPassword123",
"is_admin": false
}

Response:

{
"user_id": "xyz789",
"email": "[email protected]",
"display_name": "New User",
"is_admin": false,
"is_active": true,
"created_at": "2024-01-15T16:00:00Z"
}

Endpoint: PATCH /api/v1/auth/users/{user_id}

Request:

{
"display_name": "Updated Name",
"is_active": true,
"is_admin": false
}

Response:

{
"user_id": "xyz789",
"email": "[email protected]",
"display_name": "Updated Name",
"is_admin": false,
"is_active": true
}

Endpoint: DELETE /api/v1/auth/users/{user_id}

Response:

सफल होने पर 204 No Content लौटाता है।

Error होने पर, यह 422 Unprocessable Content और नीचे दिया JSON लौटाता है:

{
"detail": [
{
"loc": [
"string",
0
],
"msg": "string",
"type": "string"
}
]
}

Boards हर authenticated user के लिए उपलब्ध हैं; किसी board के साथ हर caller क्या कर सकता है, यह उस board पर उसकी role तय करती है।

Endpoint: GET /api/v1/boards/

Response:

{
"limit": 0,
"offset": 0,
"total": 0,
"items": [
{
"board_id": "8b31a33d-0acb-46fe-8612-83601481cf2c",
"board_name": "Testing Board",
"user_id": "string",
"created_at": "2026-05-07T03:04:00.738Z",
"updated_at": "2026-05-07T03:04:00.738Z",
"deleted_at": "2026-05-07T03:04:00.738Z",
"cover_image_name": "string",
"archived": false,
"general_access": "restricted",
"board_visibility": "private",
"my_role": "owner",
"allowed_actions": ["read", "add_media", "manage_items", "rename", "set_cover", "archive", "set_general_access", "move", "delete"],
"admin_override": false,
"image_count": 0,
"asset_count": 0,
"owner_username": "string"
}
]
}

यह एक paged response लौटाता है। Details के लिए swagger पेज (http://localhost:9090/docs#/boards/list_boards) देखें। हर board बताता है कि caller की उस तक कितनी पहुँच है:

  • general_access — वह role जो हर दूसरे user को मिलती है: restricted (कोई नहीं), viewer या contributor। सिर्फ़ owner या कोई administrator इसे PATCH /api/v1/boards/{board_id} से बदल सकता है।
  • my_role — caller की अपनी role: viewer, contributor, editor या owner; null जब सिर्फ़ administrator rights से access मिलता है।
  • allowed_actions — वे board actions जो caller कर सकता है। Clients को my_role के बजाय इस सूची के आधार पर तय करना चाहिए कि क्या पेश करें।
  • admin_override — true जब administrator rights caller को my_role से ज़्यादा देते हैं।
  • owner_username — owner का display name। Administrators बिना display name वाले owner का email देखते हैं; दूसरे users Unknown user देखते हैं।
  • project_id — सिर्फ़ board के owner और administrators को दिखाया जाता है। इसी तरह, किसी इमेज या वीडियो DTO का project_id उस project की ID देता है जिसमें वह इमेज या वीडियो बना था। यह ID केवल उस project के owner और administrators को दिखाई देती है। बाकी सभी को null मिलता है।

सिर्फ़ ऐसा board जो मौजूद नहीं है, 404 का जवाब देता है। जिस board को caller नहीं खोल सकता, वह detail {"code": "board_unreadable", "message": "Not authorized to access this board"} के साथ 403 का जवाब देता है, और जिस action की caller की role अनुमति नहीं देती, वह code board_action_denied और message Not authorized to change this board के साथ 403 का जवाब देता है: इनकार को board का owner पलट सकता है, इसलिए clients को इसे board के गायब होने के रूप में नहीं लेना चाहिए, और code message से मिलान किए बिना खोए हुए access को पुरानी role से अलग पहचानने देता है। किसी project का inbox renaming, archiving, moving, deleting और general access में बदलाव को 409 के साथ अस्वीकार करता है; ये उसके project का पालन करते हैं।

एक board प्राप्त करें

Section titled “एक board प्राप्त करें”

Endpoint: GET /api/v1/boards/{board_id}

Response:

{
"board_id": "8b31a33d-0acb-46fe-8612-83601481cf2c",
"board_name": "Testing Board",
"user_id": "3c59a0ba-f4c7-4275-b96f-82179e8aaff8",
"created_at": "2026-03-09 16:10:47.095",
"updated_at": "2026-03-09 16:10:55",
"deleted_at": null,
"cover_image_name": "08689e4b-f084-4c49-83a8-4fc1edb167c4.png",
"archived": false,
"general_access": "viewer",
"board_visibility": "shared",
"my_role": "viewer",
"allowed_actions": ["read"],
"admin_override": false,
"image_count": 55,
"asset_count": 0,
"owner_username": "Sam"
}

Projects उन्हें बनाने वाले account के लिए private होते हैं। पूरा save protocol, जिसमें content और workspace हिस्से और schema floors शामिल हैं, Project Files (.invk) में वर्णित है।

Endpoint: POST /api/v1/projects

Project और उसका inbox board बनाता है और record और workspace के साथ 201 का जवाब देता है। वैकल्पिक workspace field project में caller का पहला workspace है, यानी workspace document खुद (create का workspace हमेशा पहली row होता है, इसलिए इसमें कोई expected_revision नहीं होता), जो content के साथ उसी transaction में स्टोर होता है, ताकि कोई भी project अपने creator के workspace के बिना न बने। इसकी जाँच PUT /api/v1/projects/{project_id}/workspace की तरह होती है, सिवाय इसके कि create का max_canvas_schema_version इसे cover करता है, और इसके लिए minimum_document_schema_version का 4 या उससे ऊपर होना ज़रूरी है: पूरे document के साथ यह 400 और code workspace_needs_split_document के साथ अस्वीकार किया जाता है, और कुछ नहीं बनता। Response का workspace stored workspace (data, revision 1, updated_at) है, या null जब request में कोई workspace नहीं था।

Endpoint: PUT /api/v1/projects/{project_id}

Project का content सेव करता है और record और workspace के साथ जवाब देता है। वैकल्पिक workspace field ({data, expected_revision}) caller के workspace को उसी transaction में स्टोर करता है और उस save के लिए है जो एक पूरे project (document schema 3 या पुराना) को content और workspace में बाँटता है: तब बढ़ा हुआ document floor, content और पहली workspace row एक साथ लागू होते हैं या बिल्कुल नहीं। इसकी revision की जाँच PUT /api/v1/projects/{project_id}/workspace की तरह होती है, और mismatch होने पर पूरा save 409 और workspace के current_revision के साथ अस्वीकार कर दिया जाता है। हर दूसरे save पर इसे छोड़ दें: ऐसे save के साथ भेजा गया workspace जो document floor को 4 से नीचे छोड़ता है, 400 और code workspace_needs_split_document के साथ अस्वीकार किया जाता है। Split इसके बिना भी नहीं हो सकता: जो save floor को 4 से नीचे से 4 या उससे ऊपर ले जाता है और जिसमें workspace नहीं है, वह 400 और code split_needs_workspace के साथ अस्वीकार किया जाता है, ताकि किसी पूरे project का split caller के workspace के बिना कभी लागू न हो।

Workspace saves max_document_schema_version के साथ-साथ max_canvas_schema_version (default 2) भी declare करते हैं; project के canvas floor से नीचे वाले client को code canvas_schema_unsupported के साथ 412 मिलता है।

करें:

  • Tokens को सुरक्षित रूप से स्टोर करें (keychain, secure storage)
  • Tokens भेजने के लिए HTTPS इस्तेमाल करें
  • Logout पर tokens साफ़ करें
  • Token expiration को सहजता से संभालें

न करें:

  • Tokens को URL parameters में स्टोर करना
  • Tokens को plain text में log करना
  • Users के बीच tokens share करना
  • Tokens को version control में स्टोर करना

त्रुटियाँ सँभालना

Section titled “त्रुटियाँ सँभालना”

Authentication errors को हमेशा संभालें:

def make_request(client, func, *args, **kwargs):
max_retries = 3
retry_count = 0
while retry_count < max_retries:
try:
return func(*args, **kwargs)
except AuthenticationError:
if retry_count >= max_retries - 1:
raise
# Re-authenticate
client.login(email, password)
retry_count += 1
except Exception as e:
logger.error(f"Request failed: {e}")
raise

अनुरोधों की दर सीमित करना

Section titled “अनुरोधों की दर सीमित करना”

API rate limits का ध्यान रखें:

  • Retries के लिए exponential backoff लागू करें
  • बार-बार access किए जाने वाले data को cache करें
  • जहाँ संभव हो, requests को batch करें
  • Login endpoint पर बार-बार requests की बौछार न करें

कनेक्शन सँभालना

Section titled “कनेक्शन सँभालना”
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_session():
"""Create session with retry logic."""
session = requests.Session()
retry = Retry(
total=3,
backoff_factor=0.3,
status_forcelist=[500, 502, 503, 504],
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session

मौजूदा code अपडेट करना

Section titled “मौजूदा code अपडेट करना”

पहले (single-user mode):

import requests
def get_boards():
response = requests.get("http://localhost:9090/api/v1/boards/")
return response.json()

बाद में (multi-user mode):

import requests
class APIClient:
def __init__(self):
self.token = None
def login(self, email, password):
response = requests.post(
"http://localhost:9090/api/v1/auth/login",
json={"email": email, "password": password}
)
self.token = response.json()["token"]
def get_boards(self):
headers = {"Authorization": f"Bearer {self.token}"}
response = requests.get(
"http://localhost:9090/api/v1/boards/",
headers=headers
)
return response.json()
# Usage
client = APIClient()
client.login("[email protected]", "password")
boards = client.get_boards()

पुराने वर्ज़न के साथ संगतता

Section titled “पुराने वर्ज़न के साथ संगतता”

InvokeAI multiuser configuration option के ज़रिए single-user और multi-user, दोनों modes को सपोर्ट करता है।

Multi-user mode default है। सिर्फ़ इस computer से उपलब्ध deprecated single-user इंस्टॉल के लिए, invokeai.yaml में option को स्पष्ट रूप से सेट करें:

multiuser: false

Programmatically mode की जाँच:

def is_multiuser_enabled(base_url):
response = requests.get(f"{base_url}/api/v1/auth/status")
response.raise_for_status()
return response.json()["multiuser_enabled"]
# Example usage
base_url = "http://localhost:9090"
if is_multiuser_enabled(base_url):
print("Multi-user mode: authentication required")
# Use authenticated API calls
else:
print("Single-user mode: no authentication needed")
# Use direct API calls

Adaptive client:

class AdaptiveInvokeAIClient:
def __init__(self, base_url="http://localhost:9090"):
self.base_url = base_url
self.token = None
self.multiuser_mode = self._check_multiuser_mode()
def _check_multiuser_mode(self):
"""Detect if multi-user mode is enabled."""
try:
response = requests.get(f"{self.base_url}/api/v1/boards/")
return response.status_code == 401
except:
return False
def login(self, email, password):
"""Login (only needed in multi-user mode)."""
if not self.multiuser_mode:
print("Single-user mode: login not required")
return
response = requests.post(
f"{self.base_url}/api/v1/auth/login",
json={"email": email, "password": password}
)
self.token = response.json()["token"]
def _get_headers(self):
"""Get headers (with auth token if in multi-user mode)."""
if self.multiuser_mode and self.token:
return {"Authorization": f"Bearer {self.token}"}
return {}
def get_boards(self):
"""Get boards (works in both modes)."""
response = requests.get(
f"{self.base_url}/api/v1/boards/",
headers=self._get_headers()
)
return response.json()

Programmatic तरीके से graph चलाना

Section titled “Programmatic तरीके से graph चलाना”

अगर आप HTTP API के लिए कोई external client बना रहे हैं, तो समर्पित Workflow Execution guide देखें।

Multi-user mode में, queue और workflow requests पर अपना Authorization: Bearer <token> header शामिल करना याद रखें।

OpenAPI/Swagger डॉक्यूमेंटेशन

Section titled “OpenAPI/Swagger डॉक्यूमेंटेशन”

InvokeAI सभी endpoints के लिए OpenAPI documentation देता है।

Swagger UI खोलें:

http://localhost:9090/docs

OpenAPI schema डाउनलोड करें:

टर्मिनल विंडो
curl http://localhost:9090/openapi.json > invokeai_openapi.json

Client code जनरेट करें:

Client libraries जनरेट करने के लिए openapi-generator जैसे tools इस्तेमाल करें:

टर्मिनल विंडो
# Generate Python client
openapi-generator generate \
-i http://localhost:9090/openapi.json \
-g python \
-o ./invokeai-client
# Generate TypeScript client
openapi-generator generate \
-i http://localhost:9090/openapi.json \
-g typescript-fetch \
-o ./invokeai-client-ts

Security से जुड़ी बातें

Section titled “Security से जुड़ी बातें”

Production में हमेशा HTTPS इस्तेमाल करें:

# Development
client = InvokeAIClient("http://localhost:9090")
# Production
client = InvokeAIClient("https://invoke.example.com")

JWT tokens को सुरक्षित रखें:

# Never log tokens
logger.info(f"User logged in") # Good
logger.info(f"Token: {token}") # Bad!
# Use environment variables for credentials
import os
email = os.environ.get("INVOKEAI_EMAIL")
password = os.environ.get("INVOKEAI_PASSWORD")

User input को हमेशा validate करें:

import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def validate_password(password):
"""Check password meets requirements."""
if len(password) < 8:
return False, "Password must be at least 8 characters"
if not any(c.isupper() for c in password):
return False, "Password must contain uppercase letters"
if not any(c.islower() for c in password):
return False, "Password must contain lowercase letters"
if not any(c.isdigit() for c in password):
return False, "Password must contain numbers"
return True, ""

समस्या: “Invalid authentication credentials”

  • Token expire हो गया — फिर से authenticate करें
  • Token malformed है — token string जाँचें
  • Token signature invalid है — जाँचें कि secret key बदली तो नहीं है

समस्या: “Admin privileges required”

  • User administrator नहीं है
  • इस operation के लिए admin account इस्तेमाल करें

समस्या: Token नहीं भेजा जा रहा

  • जाँचें कि Authorization header मौजूद है
  • पुष्टि करें कि Bearer prefix शामिल है
  • जाँचें कि token कटा हुआ तो नहीं है

समस्या: CORS errors

InvokeAI में CORS कॉन्फ़िगर करें:

invokeai.yaml
allow_origins:
- "http://localhost:3000"
- "https://myapp.example.com"
allow_credentials: true
allow_methods:
- "*"
allow_headers:
- "*"

अतिरिक्त संसाधन

Section titled “अतिरिक्त संसाधन”

सवाल हैं? InvokeAI Discord पर जाएँ या FAQ देखें।