Qwen / Developer guide
Qwen API: setup, endpoints and examples
Set up a text request through Alibaba Cloud Model Studio, match your key to the correct region and workspace, and troubleshoot common failures.
By China AI Chat Team · Sources checked · Independent guide
1. Select the service and region first
This guide uses Model Studio’s general hosted API and its OpenAI-compatible Chat Completions interface. It does not configure a Qwen chat subscription, a Coding Plan or a local inference server.
- Open Alibaba Cloud Model Studio and complete the provider’s account and service setup.
- Select your region and workspace, then create a general API key with access to the selected model.
- Store that key as
DASHSCOPE_API_KEYin your server environment. - Copy the matching OpenAI-compatible base URL into an environment variable named
QWEN_BASE_URL. This variable is used by our examples; set it without a trailing slash.
For Singapore, the current official documentation shows this workspace-specific pattern:
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1Replace {WorkspaceId} with your actual workspace ID. Do not send the braces literally. The key, region and workspace must match. For another region, copy its documented endpoint from your console instead of modifying the Singapore hostname by guesswork.
Source: Alibaba Cloud first-call guide. Before running either example, confirm model access and review Qwen pricing and free-quota conditions. Each example can generate a separate usage charge.
2. Send a Python request
Install the compatible SDK in your Python environment:
python -m pip install --upgrade openaiAfter setting both environment variables, run this script. It selects qwen3.7-plus, disables thinking for a short text task and sets an output ceiling.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DASHSCOPE_API_KEY"],
base_url=os.environ["QWEN_BASE_URL"],
timeout=120.0,
max_retries=0,
)
response = client.chat.completions.create(
model="qwen3.7-plus",
messages=[{
"role": "user",
"content": "Explain a context window in two short sentences."
}],
max_completion_tokens=1024,
extra_body={"enable_thinking": False},
)
choice = response.choices[0]
print(choice.message.content or "No final answer returned.")
print("Finish reason:", choice.finish_reason)
print("Usage:", response.usage)enable_thinking is a provider-specific option. In the Python SDK it belongs in extra_body; in direct HTTP JSON it belongs at the top level. The current reference supports max_completion_tokens for this model family and defines it as the combined thinking-and-answer ceiling. Here thinking is disabled.
The example stops automatic retries so a first diagnostic call is easier to interpret. An output ceiling limits generation, not input cost or every possible application expense. Check the returned usage and your account records.
Parameter source: official Chat Completions reference. Check model-specific parameter support before switching to a different model.
3. Send the request with cURL
This uses Bash-style quoting. Both environment variables must already be set. QWEN_BASE_URL is the base ending in /v1, without the chat-completions path.
curl --fail-with-body --max-time 120 \
"$QWEN_BASE_URL/chat/completions" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"model": "qwen3.7-plus",
"messages": [{
"role": "user",
"content": "Explain a context window in two short sentences."
}],
"enable_thinking": false,
"max_completion_tokens": 1024
}'Read the answer from choices[0].message.content. Inspect finish_reason before treating the task as complete. A value of length indicates that generation reached its output limit; revise the prompt or budget before retrying.
Example status: documentation-based examples, reviewed for syntax and configuration. No authenticated live inference test or performance benchmark was performed by ChinaAI for this guide.
4. Fix common Qwen API errors
| Error | First checks |
|---|---|
| 401 InvalidApiKey | Check the variable, copied key and region. Plan-exclusive keys require their matching exclusive endpoint; do not mix them with the general API. |
| 403 Model.AccessDenied | Ask the workspace administrator to check permission for that model. A valid key alone does not establish model access. |
| 403 AllocationQuota.FreeTierOnly | The free-only allowance is exhausted. Stop or review the account’s billing choice; disabling free-only protection can enable paid usage. |
| 429 Throttling / RateQuota | Reduce request frequency and concurrency. Read the specific code to distinguish request limits from token limits. |
| 400 invalid parameter | Compare your body with the chosen model’s reference. Do not copy thinking, image or tool settings from an unrelated model. |
Source: Model Studio error reference. Preserve the request identifier and a redacted error body when investigating failures.
Before connecting this to a website
Keep the provider key on the server. Add visitor access controls, input limits, usage limits and spend monitoring before exposing a public chat form. An API key embedded in a browser page can be copied and used outside your site.
For temporary failures, use a request queue and bounded backoff. A timeout is not proof that no inference was performed: reconcile provider usage before repeating expensive calls. Log diagnostic identifiers without copying secrets or unnecessary user content into logs.
Add streaming only after a simple request succeeds. Your interface should handle an interrupted stream and show a failed request clearly. For structured data, use the documented output mode and validate the returned object before relying on it. For tools, validate arguments and retain control over any action your application executes.
See the official streaming guide and API interface index. Image generation, audio and local model serving need their own setup.
Continue with Qwen
Qwen overview · Model families and selection · API prices and free quota
ChinaAI is independent of Qwen and Alibaba Cloud. Read our methodology or report a correction.
