Developer platform

Qwen API

Developer overview for Qwen, including API access, pricing, SDK support, endpoints, capabilities and platform policies.

API key Required
Primary API OpenAI-compatible Responses API and Chat Completions API, with DashScope SDK support
SDK support Official DashScope SDK plus compatibility with official OpenAI SDKs for Python and JavaScript/TypeScript through a custom base URL. Raw HTTP is also supported.
Rate limits RPM and TPM vary by model and region. Limits are commonly aggregated at the Alibaba Cloud account and model level. Some models use dynamic TPM tiers based on monthly consumption; workspace-specific limits may also be configured. Production applications sh
Platform

API overview

Endpoints

API access

Base URL https://{WorkspaceId}.{region}.maas.aliyuncs.com/compatible-mode/v1
Primary API OpenAI-compatible Responses API and Chat Completions API, with DashScope SDK support
Pricing

API pricing

Pricing model Primarily pay-as-you-go token billing; eligible services also support batch pricing, prepaid or subscription plans, and dedicated deployment billing.

Prices vary by model, region, deployment scope, context length, caching, and thinking mode. Current examples include Qwen3.8-Max at $2 per 1 million input tokens and $6 per 1 million output tokens in the Singapore international scope. Batch inference for

Developer experience

SDKs & usability

SDKs Official DashScope SDK plus compatibility with official OpenAI SDKs for Python and JavaScript/TypeScript through a custom base URL. Raw HTTP is also supported.
Ease of use Good. OpenAI-compatible endpoints allow existing OpenAI integrations to be adapted by changing the API key, base URL, and model name. Regional workspace setup and model availability require additional configuration.
Documentation Good and actively maintained. Documentation covers quickstarts, OpenAI-compatible APIs, DashScope, model-specific references, pricing, regions, tools, structured outputs, files, fine-tuning, privacy, and migration topics.
Latency Latency varies by model, region, deployment scope, prompt size, output length, tools, and traffic. Nearby regions reduce network latency. Workspace-dedicated production endpoints provide higher isolation and documented 3600-second request timeouts in supp
Features

API capabilities

✓ Streaming
✓ Function calling
✓ Assistants API
✓ File uploads
✓ Fine-tuning
✓ Web search
✓ Image input
✓ Structured outputs
✓ Playground
Feature notes

Model Studio supports regional API keys, workspace-specific production endpoints, OpenAI-compatible Responses and Chat Completions APIs, the DashScope SDK, streaming, function calling, structured JSON output, multimodal inputs, file workflows, batch inference, fine-tuning, monitoring, and agent/application capabilities. The Responses API adds built-in tools such as web search, web extraction, code interpreter, image generation, and knowledge-base search when supported by the selected model and region. JSON Object mode is available across many models; strict JSON Schema mode is limited to selected models. Image, audio, and video capabilities vary by model. Agent application APIs and some application-development features can be restricted by region, account history, or preview status. Legacy DashScope domains remain supported in some cases, but Alibaba Cloud recommends migrating production integrations to workspace-specific regional domains. Alibaba Cloud states that the DashScope domain will not support new features after September 30, 2026.

Examples

API examples

curl -X POST "https://${WORKSPACE_ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions" \
  -H "Authorization: Bearer ${DASHSCOPE_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-max",
    "messages": [
      {"role": "system", "content": "You are a concise technical assistant."},
      {"role": "user", "content": "Explain what an API key is in one paragraph."}
    ],
    "stream": false
  }' | jq -r '.choices[0].message.content'

curl -N -X POST "https://${WORKSPACE_ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions" \
  -H "Authorization: Bearer ${DASHSCOPE_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-max",
    "messages": [{"role": "user", "content": "List three secure API-key practices."}],
    "stream": true
  }'
# Install: pip install -U openai
import json
import os
from openai import OpenAI

api_key = os.environ["DASHSCOPE_API_KEY"]
workspace_id = os.environ["WORKSPACE_ID"]

client = OpenAI(
    api_key=api_key,
    base_url=f"https://{workspace_id}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

try:
    response = client.chat.completions.create(
        model="qwen3.8-max",
        messages=[
            {"role": "system", "content": "You are a helpful technical assistant."},
            {"role": "user", "content": "Give me two practical API security recommendations."},
        ],
    )
    print(response.choices[0].message.content)

    stream = client.chat.completions.create(
        model="qwen3.8-max",
        messages=[
            {"role": "user", "content": "Explain streaming responses in simple terms."},
        ],
        stream=True,
    )
    for chunk in stream:
        text = chunk.choices[0].delta.content
        if text:
            print(text, end="", flush=True)
    print()

    structured = client.chat.completions.create(
        model="qwen3.7-plus",
        messages=[
            {"role": "system", "content": "Return the requested data as JSON."},
            {"role": "user", "content": "Return a JSON object with name and category for the product Qwen API."},
        ],
        response_format={"type": "json_object"},
    )
    print(json.loads(structured.choices[0].message.content))
except Exception as exc:
    print(f"Qwen API request failed: {exc}")
    raise
// Install: npm install openai
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DASHSCOPE_API_KEY,
  baseURL: `https://${process.env.WORKSPACE_ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1`,
});

try {
  const response = await client.chat.completions.create({
    model: "qwen3.8-max",
    messages: [
      { role: "system", content: "You are a helpful technical assistant." },
      { role: "user", content: "Explain the difference between RPM and TPM." },
    ],
  });
  console.log(response.choices[0].message.content);

  const tools = [
    {
      type: "function",
      function: {
        name: "lookup_status",
        description: "Look up the status of a service.",
        parameters: {
          type: "object",
          properties: { service: { type: "string" } },
          required: ["service"],
          additionalProperties: false,
        },
      },
    },
  ];

  const toolResponse = await client.chat.completions.create({
    model: "qwen3.8-max",
    messages: [{ role: "user", content: "Check the status of the payments service." }],
    tools,
    tool_choice: "auto",
  });

  const toolCall = toolResponse.choices[0].message.tool_calls?.[0];
  if (toolCall) {
    const args = JSON.parse(toolCall.function.arguments);
    console.log({ function: toolCall.function.name, arguments: args });
  } else {
    console.log(toolResponse.choices[0].message.content);
  }

  const stream = await client.chat.completions.create({
    model: "qwen3.8-max",
    messages: [{ role: "user", content: "Summarize the benefits of regional endpoints." }],
    stream: true,
  });
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
  }
  process.stdout.write("\n");
} catch (error) {
  console.error("Qwen API request failed:", error);
  process.exitCode = 1;
}
<?php
$apiKey = getenv('DASHSCOPE_API_KEY');
$workspaceId = getenv('WORKSPACE_ID');
$url = "https://{$workspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";

if (!$apiKey || !$workspaceId) {
    fwrite(STDERR, "DASHSCOPE_API_KEY and WORKSPACE_ID are required\n");
    exit(1);
}

$payload = [
    'model' => 'qwen3.8-max',
    'messages' => [
        ['role' => 'system', 'content' => 'You are a helpful technical assistant.'],
        ['role' => 'user', 'content' => 'Explain how to handle API rate limits.'],
    ],
];

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120,
]);

$body = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($body === false || $curlError !== '') {
    throw new RuntimeException('Network error: ' . $curlError);
}

$data = json_decode($body, true);
if ($httpCode < 200 || $httpCode >= 300) {
    $message = $data['error']['message'] ?? $body;
    throw new RuntimeException("Qwen API HTTP {$httpCode}: {$message}");
}

$content = $data['choices'][0]['message']['content'] ?? null;
if ($content === null) {
    throw new RuntimeException('The response did not contain assistant content.');
}

echo $content . PHP_EOL;
Policies

Data & usage

Data training

Alibaba Cloud Model Studio states that customer data is never used for model training. Data transmitted during application building and model training is encrypted with AES-256. Customers should still review the applicable Alibaba Cloud service terms, regional compliance requirements, workspace permissions, and logging configuration.

Data retention

Alibaba Cloud states that Model Studio stores data generated from model and application calls in compliance with applicable laws and regulations. Audit logs are enabled by default and retain request metadata such as request ID, model, token usage, latency, and status. Prompt and response content is not included in default audit logs. Full inference logs containing prompts, responses, and intermediate steps require separate enablement and are delivered to the customer's Simple Log Service Logstore. The public documentation consulted does not specify one universal retention period for all API request data.

Rate limits

RPM and TPM vary by model and region. Limits are commonly aggregated at the Alibaba Cloud account and model level. Some models use dynamic TPM tiers based on monthly consumption; workspace-specific limits may also be configured. Production applications sh

Developer guide

Qwen API: Alibaba Cloud Model Studio Developer Guide

Qwen API access is provided through Alibaba Cloud Model Studio, which offers regional OpenAI-compatible Responses and Chat Completions APIs alongside the official DashScope SDK. Developers can use API keys to access Qwen models for text and multimodal inference, streaming, function calling, structured JSON output, file workflows, built-in tools, batch processing, fine-tuning, and agent applications. Pricing is primarily pay-as-you-go and varies by model, region, deployment scope, context length, caching, and thinking mode.
Qwen API is the developer-facing interface for using Qwen models through Alibaba Cloud Model Studio. It is intended for applications that need managed model inference rather than a consumer chat interface, including chatbots, document workflows, coding tools, multimodal applications, research systems, and production services. The easiest migration path for many developers is the OpenAI-compatible API: configure a regional Model Studio endpoint, supply a regional API key, and change the model name and base URL in an existing OpenAI SDK integration.
Alibaba Cloud Model Studio provides Qwen APIs through OpenAI-compatible Responses and Chat Completions interfaces and the DashScope SDK. Developers can use regional API keys for token-priced text and multimodal inference, streaming, function calling, structured JSON, files, built-in tools, batch jobs, agents, and fine-tuning, with capabilities and limits varying by model and region.

What the Qwen API is and when to use it

The current production API platform for Qwen is Alibaba Cloud Model Studio. It provides managed access to Qwen models through regional Alibaba Cloud endpoints. You can call models over OpenAI-compatible Responses and Chat Completions APIs, use the official DashScope SDK, or send raw HTTP requests.

Use the API when your application needs repeatable programmatic access to Qwen rather than interactive use in Qwen Studio. Typical applications include conversational assistants, content generation, coding tools, document and file processing, image or other multimodal understanding, structured data extraction, tool-using agents, and batch jobs.

The Responses API is generally the better choice for new applications that need built-in tools, response items, simplified conversation state, context caching, or a mixture of text and tool results. Chat Completions remains useful for conventional message-based applications, existing OpenAI-compatible integrations, streaming, multimodal requests, and standard function calling.

Getting access and obtaining credentials

Create or access an Alibaba Cloud account, open Model Studio, choose a supported region, create a workspace, and generate an API key for that region and workspace. API keys are regional: a key created for one region cannot automatically be used with another region's endpoint.

Store the key in an environment variable or secret manager. Do not place it directly in browser code, source control, or application logs. The examples below use DASHSCOPE_API_KEY and WORKSPACE_ID.

For production, Alibaba Cloud recommends a workspace-specific regional endpoint. Common OpenAI-compatible endpoint patterns include:

  • https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1 for Singapore
  • https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1 for US Virginia
  • https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 for China Beijing

The selected region affects model availability, data-storage location, deployment scope, rate limits, and supported features. Check the current regional documentation before committing to an endpoint.

Choosing an API and model

Start by selecting the interface that matches the application rather than assuming every Qwen model supports every platform feature.

NeedSuitable starting point
Existing OpenAI-style chat integrationChat Completions with a compatible model
Built-in web, code, file, or knowledge-base toolsResponses API, when the selected model and region support them
Standard text generation or extractionA current Qwen text model through either compatible API
Images, audio, or video as inputA compatible Qwen-VL, Qwen-Omni, or other multimodal model
Alibaba-specific workflowsDashScope SDK or the relevant Model Studio API

Model identifiers, capabilities, pricing, and availability change over time. Pin a specific supported model when reproducibility matters, and monitor Alibaba Cloud deprecation notices rather than relying indefinitely on a rolling alias. Image, audio, video, tool, and structured-output support must be checked for the particular model and region.

Making the first request

The following example uses the current OpenAI Python SDK against a workspace-specific Singapore endpoint. Install the SDK with pip install -U openai, set the two environment variables, and replace the model identifier if the current regional model list requires another supported model.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DASHSCOPE_API_KEY"],
    base_url=f"https://{os.environ['WORKSPACE_ID']}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

response = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[
        {"role": "system", "content": "You are a concise technical assistant."},
        {"role": "user", "content": "Explain what an API key is in one paragraph."},
    ],
)

print(response.choices[0].message.content)

The equivalent raw HTTP request is useful for testing the endpoint independently of an SDK:

curl -X POST "https://${WORKSPACE_ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions" 
  -H "Authorization: Bearer ${DASHSCOPE_API_KEY}" 
  -H "Content-Type: application/json" 
  -d '{
    "model": "qwen3.8-max",
    "messages": [
      {"role": "user", "content": "Explain what an API key is in one paragraph."}
    ],
    "stream": false
  }'

Understanding the response

A non-streaming Chat Completions response normally contains a choices array. The assistant's generated text is available at choices[0].message.content. Usage information, when returned, can be used to track input and output tokens for cost and quota monitoring.

With streaming enabled, the server sends incremental events rather than waiting for the entire answer. This reduces perceived waiting time, but the client must assemble the partial text and handle interruptions, timeouts, and incomplete output.

Pricing, quotas, and billing

Model Studio inference is primarily pay-as-you-go. Charges generally depend on input and output token consumption, but the effective price can also vary by model, region, deployment scope, context length, caching, thinking mode, and whether the request uses batch inference.

As one documented example, Qwen3.8-Max in the Singapore international scope is listed at $2 per 1 million input tokens and $6 per 1 million output tokens. This is an example rather than a universal Qwen price; verify the current pricing page for the exact model, region, and service mode. Supported batch workloads can cost approximately 50% of real-time inference pricing. Eligible users may also receive time-limited new-user quotas in Singapore, but these should not be treated as permanent free API access.

Rate limits are commonly expressed through requests per minute and tokens per minute. Limits vary by model and region, and some models use dynamic token limits based on monthly consumption tiers. Workspace-level limits may also be configurable. Treat pricing and quotas as deployment configuration, not fixed properties of the Qwen brand.

Capabilities available to developers

Streaming responses

Chat Completions supports streaming for incremental output through supported protocols such as server-sent events. Use it for interactive interfaces or long responses, but implement cancellation, reconnect or retry policy where appropriate, and safe handling of partial answers.

stream = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[
        {"role": "user", "content": "Explain streaming responses in simple terms."}
    ],
    stream=True,
)

for chunk in stream:
    text = chunk.choices[0].delta.content
    if text:
        print(text, end="", flush=True)
print()

Function and tool calling

Function calling lets the model request an application-defined operation, such as looking up an order or checking a service. The model does not execute the function itself. Your application validates the generated arguments, performs the operation, and sends the result back for a final response.

Many Qwen text and multimodal models support function calling through the compatible APIs. Keep tools narrowly scoped, validate every argument, apply authorization independently of the model, and never treat a tool call as permission to perform an unchecked side effect.

Structured JSON output

Model Studio supports structured output features, but support differs by model and mode. JSON Object mode is broadly available across supported models, while strict JSON Schema mode is limited to selected models and modes. Multimodal structured output may fall back to JSON Object behavior.

import json

structured = client.chat.completions.create(
    model="qwen3.7-plus",
    messages=[
        {"role": "system", "content": "Return the requested data as JSON."},
        {"role": "user", "content": "Return a JSON object with name and category for Qwen API."},
    ],
    response_format={"type": "json_object"},
)

result = json.loads(structured.choices[0].message.content)
print(result)

Validate the parsed result in your application. JSON syntax alone does not guarantee that required fields, types, or business rules are correct.

Multimodal input and files

Compatible Qwen-VL, Qwen-Omni, and other models can accept supported combinations of text, images, audio, and video. Input formats may include image URLs, Base64 data URLs, or model-specific content structures. Do not assume that a model supporting image input also supports every audio, video, output, or tool feature.

File upload is available for supported extraction, batch, and fine-tuning workflows. Model Studio also documents file-oriented tools and workflows through the Responses API. Confirm file type, size, retention, region, and model support before designing a production pipeline.

Built-in tools, agents, and fine-tuning

When supported by the selected model and region, the Responses API can expose built-in tools such as web search, web extraction, code interpretation, image generation, and knowledge-base search. Model Studio also includes agent and application capabilities, knowledge-base retrieval, plugins, batch inference, and fine-tuning workflows such as supervised fine-tuning, DPO, and CPT for eligible models and regions.

These higher-level features may be restricted by region, account history, model availability, or preview status. Verify access in the current console and documentation before making them a hard dependency.

SDKs, playgrounds, and developer tools

Official integration options include the DashScope SDK, OpenAI's Python and JavaScript or TypeScript SDKs configured with a Model Studio base URL, and raw HTTP. The OpenAI-compatible route is convenient for teams that already have OpenAI-style client abstractions, while DashScope may be preferable for Alibaba-specific examples and capabilities.

Model Studio provides a console and playground-oriented development experience for testing models, managing workspaces and API keys, reviewing quotas, and configuring applications. A public playground URL was not specified in the supplied research, so console access and regional availability should be checked directly.

A practical tool-calling pattern

A safe tool-calling flow has four stages: send the user request and tool definitions, inspect the returned tool call, validate and execute the requested operation in application code, then send the tool result back to the model. Keep credentials and authorization in the application layer rather than exposing them through tool arguments.

tools = [
    {
        "type": "function",
        "function": {
            "name": "lookup_status",
            "description": "Look up the status of a service.",
            "parameters": {
                "type": "object",
                "properties": {"service": {"type": "string"}},
                "required": ["service"],
                "additionalProperties": False,
            },
        },
    }
]

response = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[{"role": "user", "content": "Check the status of the payments service."}],
    tools=tools,
    tool_choice="auto",
)

tool_call = response.choices[0].message.tool_calls[0]
if tool_call:
    arguments = json.loads(tool_call.function.arguments)
    # Validate arguments and call your own service here.
    print(tool_call.function.name, arguments)

The snippet demonstrates inspection only. A complete implementation must return the tool result in the message format required by the selected API and then request the model's final answer.

Limits and production considerations

  • Regional dependency: Endpoint, key, model availability, data location, limits, and feature support are tied to region and workspace.
  • Changing model catalog: Alibaba Cloud retires legacy models and changes aliases. Track deprecation notices and maintain a migration path.
  • Rate limiting: Handle HTTP 429 responses with bounded exponential backoff, avoid unbounded retries, and monitor RPM, TPM, latency, and token usage.
  • Feature variation: Provider-level capabilities are not available through every model. Test multimodal input, tools, structured output, and built-in tools with the exact production model.
  • Reliability and latency: Latency depends on model, region, prompt size, output length, tools, traffic, and deployment scope. Nearby regions can reduce network delay. Supported dedicated and standard regional endpoints have documented 99.9% SLA coverage, while trial endpoints do not provide an SLA.
  • Privacy and logs: Alibaba Cloud states that Model Studio customer data is not used for model training. Default audit logs contain request metadata such as model, token usage, latency, status, and request ID, not prompt and response content. Full inference logs require separate enablement and are delivered to the customer's Simple Log Service Logstore.
  • Retention: The supplied public documentation does not specify one universal retention period for all API request data, so review the applicable service terms and regional requirements.

When Qwen API is a good or poor choice

Qwen API is a good fit when you want Qwen models through a managed Alibaba Cloud platform, need OpenAI-compatible migration options, operate in a supported Alibaba Cloud region, or need a combination of text, multimodal input, tools, files, batch processing, and fine-tuning. Its regional workspace model is also useful when endpoint location and cloud-account controls matter.

It may be a poor fit when your target users or infrastructure are in regions without dependable access, when you require a single globally uniform model catalog and feature set, or when your application depends on a specific capability that is only available in a preview or one region. It is also not a substitute for application-level validation: generated content, tool arguments, and structured data still require appropriate checks before use.

Sources 17