### POST /api/setup - Complete Initial Installation Wizard Source: https://docs.newapi.pro/ja/api/fei-system-initialization Completes the initial system setup by creating the root administrator account and finalizing configuration. ```APIDOC ## POST /api/setup ### Description Initializes the system by creating the root administrator account with the provided credentials and settings. This endpoint is used for the first-time setup of the system. ### Method POST ### Endpoint /api/setup ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - The desired username for the root administrator. Maximum length is 12 characters. - **password** (string) - Required - The password for the root administrator. Minimum length is 8 characters. - **confirmPassword** (string) - Required - Confirmation of the password. Must match the password field. - **SelfUseModeEnabled** (boolean) - Optional - Whether to enable self-use mode. - **DemoSiteEnabled** (boolean) - Optional - Whether to enable demo site mode. ### Request Example ```javascript const response = await fetch('/api/setup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: "admin", password: "password123", confirmPassword: "password123", SelfUseModeEnabled: false, DemoSiteEnabled: false }) }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - True indicating successful initialization. - **message** (string) - A confirmation message, e.g., "System initialization complete." #### Response Example ```json { "success": true, "message": "システム初期化完了" } ``` #### Error Response (e.g., 400) - **success** (boolean) - False indicating an error. - **message** (string) - A message describing the error, e.g., "Username length must not exceed 12 characters." #### Error Response Example ```json { "success": false, "message": "ユーザー名の長さは12文字を超えてはなりません" } ``` ``` -------------------------------- ### Get System Runtime Status (JavaScript) Source: https://docs.newapi.pro/api/fei-system-initialization Fetches the current system runtime status, including version, start time, email verification status, OAuth configuration, and feature flags. This is a public endpoint. ```javascript const response = await fetch('/api/status', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` -------------------------------- ### Docker Compose Simplified Configuration for Testing Source: https://docs.newapi.pro/installation/docker-compose-yml A simplified Docker Compose configuration for testing purposes, only including the New API service. This setup is minimal and does not include database dependencies. ```yaml services: new-api: image: calciumion/new-api:latest container_name: new-api restart: always ports: - "3000:3000" environment: - TZ=Asia/Shanghai volumes: - ./data:/data ``` -------------------------------- ### GET /api/setup - Get System Initialization Status Source: https://docs.newapi.pro/ja/api/fei-system-initialization Checks the system's initialization status, including database type and root user initialization. ```APIDOC ## GET /api/setup ### Description Retrieves the current initialization status of the system, indicating whether it has been completed, the type of database configured, and if the root user has been initialized. ### Method GET ### Endpoint /api/setup ### Parameters #### Query Parameters None ### Request Example ```javascript const response = await fetch('/api/setup', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the system status details. - **status** (boolean) - True if the system initialization is complete, false otherwise. - **root_init** (boolean) - True if the root user has been initialized, false otherwise. - **database_type** (string) - The type of database configured (e.g., "mysql", "postgres", "sqlite"). #### Response Example ```json { "success": true, "data": { "status": false, "root_init": true, "database_type": "sqlite" } } ``` #### Error Response (e.g., 500) - **success** (boolean) - False indicating an error. - **message** (string) - A message describing the error. #### Error Response Example ```json { "success": false, "message": "システムエラー" } ``` ``` -------------------------------- ### GET /api/status - Get System Runtime Status Summary Source: https://docs.newapi.pro/api/fei-system-initialization Retrieves the system's runtime status, configuration information, and feature toggle states. This endpoint is publicly accessible. ```APIDOC ## GET /api/status ### Description Retrieves the system's runtime status, configuration information, and feature toggle states. ### Method GET ### Endpoint /api/status ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```javascript const response = await fetch('/api/status', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - An empty string if successful. - **data** (object) - Contains the system status details. - **version** (string) - The system version number. - **start_time** (number) - The system startup timestamp. - **email_verification** (boolean) - Whether email verification is enabled. - **github_oauth** (boolean) - Whether GitHub OAuth login is enabled. - **github_client_id** (string) - The GitHub OAuth client ID. - **system_name** (string) - The name of the system. - **quota_per_unit** (number) - The quota amount per unit. - **display_in_currency** (boolean) - Whether to display in currency. - **enable_drawing** (boolean) - Whether drawing functionality is enabled. - **enable_task** (boolean) - Whether task functionality is enabled. - **setup** (boolean) - Indicates if the system has completed initialization. #### Response Example ```json { "success": true, "message": "", "data": { "version": "v1.0.0", "start_time": 1640995200, "email_verification": false, "github_oauth": true, "github_client_id": "your_client_id", "system_name": "New API", "quota_per_unit": 500000, "display_in_currency": true, "enable_drawing": true, "enable_task": true, "setup": true } } ``` #### Error Response (4xx/5xx) - **success** (boolean) - Indicates if the request was successful (will be false). - **message** (string) - A message describing the error (e.g., "获取状态失败"). #### Error Response Example ```json { "success": false, "message": "获取状态失败" } ``` ``` -------------------------------- ### GET /api/setup - Get System Initialization Status Source: https://docs.newapi.pro/api/fei-system-initialization Checks if the system has completed initialization and retrieves the database type and root user status. This endpoint is publicly accessible. ```APIDOC ## GET /api/setup ### Description Checks if the system has completed initialization, and retrieves the database type and root user status. ### Method GET ### Endpoint /api/setup ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```javascript const response = await fetch('/api/setup', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the initialization status details. - **status** (boolean) - Indicates if the system has completed initialization. - **root_init** (boolean) - Indicates if the root user has been initialized. - **database_type** (string) - The type of database being used (e.g., "mysql", "postgres", "sqlite"). #### Response Example ```json { "success": true, "data": { "status": false, "root_init": true, "database_type": "sqlite" } } ``` #### Error Response (4xx/5xx) - **success** (boolean) - Indicates if the request was successful (will be false). - **message** (string) - A message describing the error. #### Error Response Example ```json { "success": false, "message": "系统错误" } ``` ``` -------------------------------- ### Polling Strategy and Example Source: https://docs.newapi.pro/api/query-video Recommended polling intervals and an example code snippet for polling video generation status. ```APIDOC ## Polling Strategy ### Recommended Polling Intervals 1. **Initial Poll**: Wait 2-3 seconds after submitting a task before starting to poll. 2. **Polling Frequency**: - First 30 seconds: Poll every 5 seconds. - 30 seconds to 2 minutes: Poll every 10 seconds. - After 2 minutes: Poll every 30 seconds. 3. **Timeout Handling**: It is recommended to set a total timeout of 5-10 minutes. ### Polling Example Code ```javascript async function pollVideoStatus(taskId, maxAttempts = 30) { const baseUrl = 'https://your-newapi-server-address'; const headers = { 'Authorization': 'Bearer sk-xxxx', 'Content-Type': 'application/json' }; for (let attempt = 0; attempt < maxAttempts; attempt++) { try { const response = await fetch(`${baseUrl}/v1/video/generations/${taskId}`, { headers }); const result = await response.json(); if (result.status === 'succeeded') { return result; } else if (result.status === 'failed') { throw new Error(`Video generation failed: ${result.error?.message || 'Unknown error'}`); } // Wait before retrying const delay = attempt < 6 ? 5000 : (attempt < 12 ? 10000 : 30000); await new Promise(resolve => setTimeout(resolve, delay)); } catch (error) { console.error(`Attempt ${attempt + 1} failed:`, error); if (attempt === maxAttempts - 1) { throw error; } } } throw new Error('Max polling attempts reached'); } ``` ``` -------------------------------- ### GET /api/status - Get Operational Status Overview Source: https://docs.newapi.pro/ja/api/fei-system-initialization Retrieves an overview of the system's operational status, including configuration details and feature switch states. ```APIDOC ## GET /api/status ### Description Fetches the real-time operational status of the system, providing details on version, uptime, feature flags, and configuration settings. ### Method GET ### Endpoint /api/status ### Parameters #### Query Parameters None ### Request Example ```javascript const response = await fetch('/api/status', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - An empty string if successful. - **data** (object) - Contains the system status details. - **version** (string) - The system version number. - **start_time** (number) - The system startup timestamp. - **email_verification** (boolean) - Whether email verification is enabled. - **github_oauth** (boolean) - Whether GitHub OAuth login is enabled. - **github_client_id** (string) - The GitHub OAuth client ID. - **system_name** (string) - The name of the system. - **quota_per_unit** (number) - The quota quantity per unit. - **display_in_currency** (boolean) - Whether to display in currency format. - **enable_drawing** (boolean) - Whether the drawing feature is enabled. - **enable_task** (boolean) - Whether the task feature is enabled. - **setup** (boolean) - Whether the system has completed its initial setup. #### Response Example ```json { "success": true, "message": "", "data": { "version": "v1.0.0", "start_time": 1640995200, "email_verification": false, "github_oauth": true, "github_client_id": "your_client_id", "system_name": "New API", "quota_per_unit": 500000, "display_in_currency": true, "enable_drawing": true, "enable_task": true, "setup": true } } ``` #### Error Response (e.g., 500) - **success** (boolean) - False indicating an error. - **message** (string) - A message describing the error, e.g., "Failed to retrieve status." #### Error Response Example ```json { "success": false, "message": "ステータスの取得に失敗しました" } ``` ``` -------------------------------- ### Jimeng AI Video Generation Example (cURL) Source: https://docs.newapi.pro/api/generate-video Example cURL command to generate a video using the Jimeng AI model. Demonstrates text-to-video and image-to-video generation with specific metadata parameters. ```curl curl https://你的newapi服务器地址/v1/video/generations \ --request POST \ --header 'Authorization: Bearer sk-xxxx' \ --header 'Content-Type: application/json' \ --data '{ "model": "jimeng_vgfm_t2v_l20", "prompt": "一个穿着宇航服的宇航员在月球上行走", "image": "https://h2.inkwai.com/bs2/upload-ylab-stunt/se/ai_portal_queue_mmu_image_upscale_aiweb/3214b798-e1b4-4b00-b7af-72b5b0417420_raw_image_0.jpg", "metadata": { "req_key": "jimeng_vgfm_i2v_l20", "image_urls": [ "https://h2.inkwai.com/bs2/upload-ylab-stunt/se/ai_portal_queue_mmu_image_upscale_aiweb/3214b798-e1b4-4b00-b7af-72b5b0417420_raw_image_0.jpg" ], "aspect_ratio": "16:9" } }' ``` -------------------------------- ### Kling AI Video Generation Example (cURL) Source: https://docs.newapi.pro/api/generate-video Example cURL command to generate a video using the Kling AI model. Includes prompt, size, image input, duration, and custom metadata. ```curl curl https://你的newapi服务器地址/v1/video/generations \ --request POST \ --header 'Authorization: Bearer sk-xxxx' \ --header 'Content-Type: application/json' \ --data '{ "model": "kling-v1", "prompt": "一个穿着宇航服的宇航员在月球上行走, 高品质, 电影级", "size": "1920x1080", "image": "https://h2.inkwai.com/bs2/upload-ylab-stunt/se/ai_portal_queue_mmu_image_upscale_aiweb/3214b798-e1b4-4b00-b7af-72b5b0417420_raw_image_0.jpg", "duration": 5, "metadata": { "seed": 20231234, "negative_prompt": "模糊", "image_tail": "https://h1.inkwai.com/bs2/upload-ylab-stunt/1fa0ac67d8ce6cd55b50d68b967b3a59.png" } }' ``` -------------------------------- ### Vidu Channel Video Generation Example (cURL) Source: https://docs.newapi.pro/api/generate-video Example cURL command for generating video using the Vidu channel. Shows parameters like resolution, duration, and callback URL. ```curl curl https://你的newapi服务器地址/v1/video/generations \ --request POST \ --header 'Authorization: Bearer sk-xxxx' \ --header 'Content-Type: application/json' \ --data '{ "model": "viduq1", "prompt": "一个穿着宇航服的宇航员在月球上行走, 高品质, 电影级", "size": "1920x1080", "image": "https://prod-ss-images.s3.cn-northwest-1.amazonaws.com.cn/vidu-maas/template/image2video.png", "duration": 5, "metadata": { "duration": 5, "seed": 0, "resolution": "1080p", "movement_amplitude": "auto", "bgm": false, "payload": "", "callback_url": "https://your-callback-url.com/webhook" } }' ``` -------------------------------- ### Partially Filled Response Example Source: https://docs.newapi.pro/api/anthropic-chat Shows an example of a partially filled assistant response. This can be used to guide or constrain the model's next output. ```json [ {"role": "user", "content": "太阳的希腊语名字是什么? (A) Sol (B) Helios (C) Sun"}, {"role": "assistant", "content": "正确答案是 ("} ] ``` -------------------------------- ### Messages API - Basic Usage Source: https://docs.newapi.pro/api/anthropic-chat An example of sending a simple user message to the API to get a response from the assistant. ```APIDOC ## POST /v1/messages ### Description Sends a message or a series of messages to the Claude model to generate a conversational response. ### Method POST ### Endpoint /v1/messages ### Parameters #### Request Body - **model** (string) - Required - The name of the model to use. - **messages** (array of objects) - Required - A list of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender (user or assistant). - **content** (string or array of objects) - Required - The content of the message. - **max_tokens** (integer) - Required - The maximum number of tokens to generate in the response. - **temperature** (number) - Optional - Controls the randomness of the generated output (0.0 to 1.0). - **system** (string) - Optional - A system prompt to provide context and instructions to the model. - **tool_choice** (object) - Optional - Controls how the model uses provided tools. - **stream** (boolean) - Optional - Whether to use Server-Sent Events (SSE) for incremental responses. - **stop_sequences** (array of strings) - Optional - Custom stop sequences for generated text. - **metadata** (object) - Optional - Metadata associated with the request. - **thinking** (object) - Optional - Configuration for Claude's extended thinking feature. ### Request Example ```json { "model": "claude-3-opus-20240229", "max_tokens": 1024, "messages": [ { "role": "user", "content": "Hello, Claude" } ] } ``` ### Response #### Success Response (200) - **content** (array of objects) - The response content from the model. - **role** (string) - The role of the sender of the message (assistant). - **stop_reason** (string) - The reason the model stopped generating text. - **stop_sequence** (string or null) - The stop sequence that was triggered, if any. - **id** (string) - The unique identifier for the message. - **model** (string) - The model used for generation. - **usage** (object) - Information about token usage. #### Response Example ```json { "content": [ { "type": "text", "text": "Hello! How can I help you today?" } ], "role": "assistant", "stop_reason": "end_turn", "stop_sequence": null, "id": "msg_abc123", "model": "claude-3-opus-20240229", "usage": { "input_tokens": 10, "output_tokens": 15 } } ``` ``` -------------------------------- ### POST /api/setup - Complete First-Time Installation Wizard Source: https://docs.newapi.pro/api/fei-system-initialization Creates the root administrator account and completes the initial system configuration. This endpoint is publicly accessible. ```APIDOC ## POST /api/setup ### Description Creates the root administrator account and completes the initial system configuration. ### Method POST ### Endpoint /api/setup ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - Administrator username (max 12 characters). - **password** (string) - Required - Administrator password (min 8 characters). - **confirmPassword** (string) - Required - Password confirmation, must match the password field. - **SelfUseModeEnabled** (boolean) - Optional - Whether to enable self-use mode. - **DemoSiteEnabled** (boolean) - Optional - Whether to enable demo site mode. ### Request Example ```javascript const response = await fetch('/api/setup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: "admin", password: "password123", confirmPassword: "password123", SelfUseModeEnabled: false, DemoSiteEnabled: false }) }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - A success message (e.g., "系统初始化完成"). #### Response Example ```json { "success": true, "message": "系统初始化完成" } ``` #### Error Response (4xx/5xx) - **success** (boolean) - Indicates if the request was successful (will be false). - **message** (string) - A message describing the error (e.g., "用户名长度不能超过12个字符"). #### Error Response Example ```json { "success": false, "message": "用户名长度不能超过12个字符" } ``` ``` -------------------------------- ### Complete First Installation Wizard (JavaScript) Source: https://docs.newapi.pro/api/fei-system-initialization Completes the first installation wizard by creating the root administrator account and initializing system configuration. This is a public endpoint. It requires username, password, and confirmation password in the request body. ```javascript const response = await fetch('/api/setup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: "admin", password: "password123", confirmPassword: "password123", SelfUseModeEnabled: false, DemoSiteEnabled: false }) }); const data = await response.json(); ``` -------------------------------- ### Docker Compose Environment Variables Setup Source: https://docs.newapi.pro/installation/environment-variables Example of setting environment variables for a service within a Docker Compose file. This includes timezone, database connection, Redis connection, security secrets, and various service-specific configurations. ```yaml services: new-api: image: calciumion/new-api:latest environment: - TZ=Asia/Shanghai - SQL_DSN=root:123456@tcp(mysql:3306)/oneapi - REDIS_CONN_STRING=redis://default:redispw@redis:6379 - SESSION_SECRET=your_unique_session_secret - CRYPTO_SECRET=your_unique_crypto_secret - MEMORY_CACHE_ENABLED=true - GENERATE_DEFAULT_TOKEN=true - STREAMING_TIMEOUT=120 - CHANNEL_UPDATE_FREQUENCY=1440 ``` -------------------------------- ### Query Video Generation Status (curl) Source: https://docs.newapi.pro/api/kling-jimeng Example using curl to query the status and results of a video generation task using its unique task ID. This is a GET request to the /v1/video/generations/{task_id} endpoint. ```curl curl 'https://你的newapi服务器地址/v1/video/generations/{task_id}' ``` -------------------------------- ### Test Backend and Dependencies (JavaScript) Source: https://docs.newapi.pro/api/fei-system-initialization Tests the connectivity and health of various system components, including the database, Redis, and external APIs. This endpoint requires administrator authentication. ```javascript const response = await fetch('/api/status/test', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_admin_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` -------------------------------- ### Telegram Account Binding Failure Response (JSON) Source: https://docs.newapi.pro/api/fei-oauth-third-party-login Provides an example of a failed JSON response during Telegram account binding. It indicates that the Telegram account is already linked to another user. This message should guide the user on how to proceed. ```json { "success": false, "message": "该Telegram账户已被绑定" } ``` -------------------------------- ### GET /api/status/test - Test Backend and Dependent Components Source: https://docs.newapi.pro/api/fei-system-initialization Tests the connection status and health of various system components, including the database and external APIs. Requires administrator authentication. ```APIDOC ## GET /api/status/test ### Description Tests the system's component connection status and health. Requires administrator authentication. ### Method GET ### Endpoint /api/status/test ### Parameters #### Path Parameters None #### Query Parameters None #### Headers - **Authorization** (string) - Required - Bearer token for administrator authentication. - **New-Api-User** (string) - Required - The user ID for the administrator. ### Request Example ```javascript const response = await fetch('/api/status/test', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_admin_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - A success message (e.g., "所有组件测试通过"). - **data** (object) - Contains the status of different components. - **database** (string) - The database connection status (e.g., "connected"). - **redis** (string) - The Redis connection status (e.g., "connected"). - **external_apis** (string) - The health status of external APIs (e.g., "healthy"). #### Response Example ```json { "success": true, "message": "所有组件测试通过", "data": { "database": "connected", "redis": "connected", "external_apis": "healthy" } } ``` #### Error Response (4xx/5xx) - **success** (boolean) - Indicates if the request was successful (will be false). - **message** (string) - A message describing the error (e.g., "数据库连接失败"). #### Error Response Example ```json { "success": false, "message": "数据库连接失败" } ``` ``` -------------------------------- ### Telegram Account Binding API Request (JavaScript) Source: https://docs.newapi.pro/api/fei-oauth-third-party-login Illustrates how to initiate a GET request to bind a Telegram account to an existing user profile. The example assumes `telegram_auth_params` are automatically handled, likely by a component. Dependencies: `fetch` API. ```javascript // 通过TelegramLoginButton组件自动处理参数 // 参数格式与Telegram登录相同 const response = await fetch('/api/oauth/telegram/bind', { method: 'GET', params: telegram_auth_params }); const data = await response.json(); ``` -------------------------------- ### Uptime-Kuma Compatible Status Probe (JavaScript) Source: https://docs.newapi.pro/api/fei-system-initialization Provides a status check endpoint compatible with Uptime-Kuma monitoring systems. It returns information about monitored services and their status. ```javascript const response = await fetch('/api/uptime/status', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` -------------------------------- ### Get Random State API Request (JavaScript) Source: https://docs.newapi.pro/api/fei-oauth-third-party-login Example of a JavaScript `fetch` request to obtain a random state parameter for CSRF protection in OAuth flows. It optionally includes an affiliate code (`aff`) from local storage. Dependencies: `fetch` API, `localStorage`. ```javascript let path = '/api/oauth/state'; let affCode = localStorage.getItem('aff'); if (affCode && affCode.length > 0) { path += `?aff=${affCode}`; } const response = await fetch(path, { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` -------------------------------- ### Configure Umami Website ID and Script URL via Environment Variable Source: https://docs.newapi.pro/wiki/analytics-setup Configure Umami Analytics integration by setting the Website ID and optionally the Script URL. This allows New API to track user behavior using Umami. The Website ID is obtained from your Umami setup (Cloud or self-hosted). ```yaml environment: - UMAMI_WEBSITE_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx # Optional: Only needed for self-hosted instances - UMAMI_SCRIPT_URL=https://your-umami-domain.com/script.js ``` ```shell export UMAMI_WEBSITE_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx export UMAMI_SCRIPT_URL=https://your-umami-domain.com/script.js # Optional ``` -------------------------------- ### GET /api/uptime/status - Uptime-Kuma Compatible Status Probe Source: https://docs.newapi.pro/api/fei-system-initialization Provides a status check endpoint compatible with the Uptime-Kuma monitoring system. This endpoint is publicly accessible. ```APIDOC ## GET /api/uptime/status ### Description Provides a status check endpoint compatible with the Uptime-Kuma monitoring system. ### Method GET ### Endpoint /api/uptime/status ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```javascript const response = await fetch('/api/uptime/status', { method: 'GET', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (array) - A list of monitor categories and their status. - **categoryName** (string) - The name of the monitor category. - **monitors** (array) - A list of monitor items within the category. - **name** (string) - The name of the monitor item. - **group** (string) - The group name for the monitor. - **status** (number) - The status code (1 for normal, 0 for abnormal). - **uptime** (number) - The uptime percentage. #### Response Example ```json { "success": true, "data": [ { "categoryName": "OpenAI服务", "monitors": [ { "name": "GPT-4", "group": "OpenAI", "status": 1, "uptime": 99.5 } ] } ] } ``` #### Error Response (4xx/5xx) - **success** (boolean) - Indicates if the request was successful (will be false). - **message** (string) - A message describing the error (e.g., "获取监控数据失败"). #### Error Response Example ```json { "success": false, "message": "获取监控数据失败" } ``` ``` -------------------------------- ### POST /api/option/migrate_console_setting Source: https://docs.newapi.pro/api/fei-site-configuration Migrates console settings from older versions to the new configuration format. This includes API information, announcements, and FAQs. ```APIDOC ## POST /api/option/migrate_console_setting ### Description Migrates console settings from older versions to the new configuration format. This includes API information, announcements, and FAQs. ### Method POST ### Endpoint /api/option/migrate_console_setting ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const response = await fetch('/api/option/migrate_console_setting', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_root_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the migration was successful. - **message** (string) - A confirmation message, e.g., "migrated". #### Response Example ```json { "success": true, "message": "migrated" } ``` #### Error Response (e.g., 400, 401, 500) - **success** (boolean) - Indicates if the migration was successful (false in case of error). - **message** (string) - An error message describing the failure, e.g., "迁移失败". #### Error Response Example ```json { "success": false, "message": "迁移失败" } ``` ### Notes Migration includes: - `ApiInfo` → `console_setting.api_info` - `Announcements` → `console_setting.announcements` - `FAQ` → `console_setting.faq` - `UptimeKumaUrl/UptimeKumaSlug` → `console_setting.uptime_kuma_groups` ``` -------------------------------- ### GET /api/user/ - Get All Users Source: https://docs.newapi.pro/api/fei-user Retrieves a paginated list of all users in the system. Requires administrator authentication. ```APIDOC ## GET /api/user/ ### Description Retrieves a paginated list of all users in the system. Requires administrator authentication. ### Method GET ### Endpoint /api/user/ ### Parameters #### Query Parameters - **p** (integer) - Optional - Page number, defaults to 1. - **page_size** (integer) - Optional - Number of items per page, defaults to 20. ### Request Example ```json { "query": { "p": 1, "page_size": 20 } } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - An empty string if successful. - **data** (object) - Contains user list information. - **items** (array) - List of user objects. - **id** (integer) - User ID. - **username** (string) - User's username. - **display_name** (string) - User's display name. - **role** (integer) - User's role. - **status** (integer) - User's status. - **email** (string) - User's email address. - **group** (string) - User's group. - **quota** (integer) - User's quota. - **used_quota** (integer) - User's used quota. - **request_count** (integer) - User's request count. - **total** (integer) - Total number of users. - **page** (integer) - Current page number. - **page_size** (integer) - Number of items per page. #### Response Example ```json { "success": true, "message": "", "data": { "items": [ { "id": 1, "username": "testuser", "display_name": "Test User", "role": 1, "status": 1, "email": "user@example.com", "group": "default", "quota": 1000000, "used_quota": 50000, "request_count": 100 } ], "total": 50, "page": 1, "page_size": 20 } } ``` #### Error Response (400) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A message describing the error. #### Error Response Example ```json { "success": false, "message": "获取用户列表失败" } ``` ``` -------------------------------- ### Register New Account (JavaScript) Source: https://docs.newapi.pro/api/fei-user Creates a new user account. Supports email verification and referral codes. Requires username, password, and optionally email, verification_code, and aff_code. ```javascript const response = await fetch('/api/user/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: "newuser", password: "password123", email: "user@example.com", verification_code: "123456", aff_code: "INVITE123" }) }); const data = await response.json(); ``` -------------------------------- ### GET /api/user/models - Get Model Visibility Source: https://docs.newapi.pro/api/fei-user Retrieves the list of AI models that the current user can access. ```APIDOC ## GET /api/user/models ### Description Retrieves the list of AI models that the current user can access. ### Method GET ### Endpoint /api/user/models ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const response = await fetch('/api/user/models', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_user_token', 'New-Api-User': 'your_user_id' } }); const data = await response.json(); ``` ### Response #### Success Response (200) - **data** (array) - A list of model names the user can access. #### Response Example ```json { "success": true, "message": "", "data": [ "gpt-3.5-turbo", "gpt-4", "claude-3-sonnet", "claude-3-haiku" ] } ``` #### Error Response (4xx/5xx) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - Error message. #### Error Response Example ```json { "success": false, "message": "获取模型列表失败" } ``` ### Field Descriptions - `data` (array): List of model names accessible by the user. ``` -------------------------------- ### Chat Completion Response Example Source: https://docs.newapi.pro/api/openai-chat This section provides an example of the response structure when requesting a single chat completion. ```APIDOC ## Chat Completion Response Example ### Description This is an example of a successful response from the chat completion endpoint, detailing a single generated message. ### Method POST ### Endpoint /v1/chat/completions ### Response #### Success Response (200) - **id** (string) - Unique identifier for the chat completion. - **object** (string) - The type of object, which is `chat.completion`. - **created** (integer) - Unix timestamp (in seconds) of when the completion was created. - **model** (string) - The model used for the completion. - **choices** (array) - A list of completion choices. Each choice contains: - **index** (integer) - The index of the choice in the list. - **message** (object) - The generated message content. - **role** (string) - The role of the message author (e.g., `assistant`). - **content** (string) - The text content of the message. - **refusal** (null) - Placeholder for refusal information, typically null. - **annotations** (array) - Annotations associated with the message, if any. - **logprobs** (null) - Placeholder for log probabilities, typically null. - **finish_reason** (string) - The reason the model stopped generating. - **usage** (object) - An object detailing the token usage for the request. - **prompt_tokens** (integer) - Number of tokens in the prompt. - **completion_tokens** (integer) - Number of tokens in the completion. - **total_tokens** (integer) - Total number of tokens used. - **prompt_tokens_details** (object) - Detailed breakdown of prompt tokens. - **completion_tokens_details** (object) - Detailed breakdown of completion tokens. - **service_tier** (string) - The service tier used for the request. - **system_fingerprint** (string) - A system-generated fingerprint for the response. #### Response Example ```json { "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG", "object": "chat.completion", "created": 1741570283, "model": "gpt-4o-2024-08-06", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "图片展示了一条穿过茂密绿色草地或草甸的木制栈道。天空湛蓝,点缀着几朵散落的云彩,给整个场景营造出宁静祥和的氛围。背景中可以看到树木和灌木丛。", "refusal": null, "annotations": [] }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 1117, "completion_tokens": 46, "total_tokens": 1163, "prompt_tokens_details": { "cached_tokens": 0, "audio_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 0, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "service_tier": "default", "system_fingerprint": "fp_fc9f1d7035" } ``` ``` -------------------------------- ### Update New API from Source Code Source: https://docs.newapi.pro/installation/system-update Updates the New API system when deployed from source code. This process involves pulling the latest code changes, recompiling the backend and frontend, and then restarting the service. Ensure you are in the project directory. ```bash cd new-api git pull # Compile backend go build -o new-api # Update and compile frontend cd web bun install bun run build cd .. # Restart service ./new-api --port 3000 ``` -------------------------------- ### Code Execution Example Source: https://docs.newapi.pro/api/google-gemini-chat An example demonstrating how the model can generate and execute code to solve problems, such as calculating Fibonacci numbers. ```APIDOC ## Code Execution Example ### Description This example showcases the Gemini API's code execution capability, where the model generates Python code to compute the 10th Fibonacci number and displays the result. ### Method POST ### Endpoint /v1beta/models/{model}:generateContent ### Parameters #### Request Body - **contents** (array) - Required - The content to generate responses from. - **parts** (array) - Required - The content parts of the prompt. - **text** (string) - The text part of the prompt. - **executableCode** (object) - The code to be executed. - **language** (string) - Required - The programming language of the code. (e.g., PYTHON) - **code** (string) - Required - The code to execute. ### Request Example ```json { "contents": [ { "parts": [ { "text": "Calculate the 10th item of the Fibonacci sequence:" }, { "executableCode": { "language": "PYTHON", "code": "def fibonacci(n):\n if n <= 1:\n return n\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\nresult = fibonacci(10)\nprint(f'The 10th Fibonacci number is: {result}')" } } ] } ] } ``` ### Response #### Success Response (200) - **candidates** (array) - Response candidates. - **content** (object) - The content of the response. - **parts** (array) - The parts of the content. - **text** (string) - Text generated by the model. - **codeExecutionResult** (object) - The result of code execution. - **outcome** (string) - The outcome of the execution (e.g., OK). - **output** (string) - The standard output of the execution. - **role** (string) - The role of the message sender (e.g., model). - **finishReason** (string) - The reason why the model stopped generating the response. #### Response Example ```json { "candidates": [ { "content": { "parts": [ { "text": "I will calculate the 10th item of the Fibonacci sequence:" }, { "codeExecutionResult": { "outcome": "OK", "output": "The 10th Fibonacci number is: 55" } }, { "text": "So the 10th item of the Fibonacci sequence is 55." } ], "role": "model" }, "finishReason": "STOP" } ] } ``` ```