The Qwen API lets your software send requests to Qwen models for tasks such as text generation, classification, and information extraction. Start with the official Qwen API Platform and its QwenCloud developer documentation, then create a key and use the endpoint documented for that key.
This independent guide uses QwenCloud pay-as-you-go access for a complete first request. It also explains when Alibaba Cloud Model Studio or another hosting route needs different settings. You do not need to run every example: choose cURL or Python after checking your account’s billing and model access.
Choose the right Qwen API access route
Choose where your request will run before copying code. The model name alone does not identify the correct account, credentials, endpoint, or billing arrangement.
| Access route | What to configure |
|---|---|
| QwenCloud | Use the account, key, and API host described in the official QwenCloud quickstart. This is the route used below. |
| Alibaba Cloud Model Studio | Activate the service and obtain the correct region and workspace settings from the Model Studio quickstart. Do not substitute its endpoint into this guide without also checking the key and model. |
| Third-party hosting | A service such as OpenRouter has its own credentials, model identifiers, routing, and billing. Follow that provider’s documentation. |
| Self-hosting | Deploy a supported model using the runtimes covered in the Qwen deployment documentation. You manage the server, endpoint, and operating costs; downloadable weights are not free hosted inference. |
A chat login or subscription is not enough to identify API access. QwenCloud also offers a separate Token Plan for supported tools and integrations. Its sk-sp- keys use a different host from pay-as-you-go keys. Check the plan’s permitted use and key-type requirements; do not place a Token Plan key into the pay-as-you-go example below.
Is the Qwen API free? Check billing before your first call
Do not assume unlimited free API access. QwenCloud’s current free-quota rules require eligible new users to complete and verify payment information. Allowances are model-specific, combine input and output tokens, and typically expire after 90 days. Check the console for your model’s actual remaining allowance and expiration date.
On the console’s Free Tier page, enable Free quota only for the model before testing when you want covered calls to stop rather than continue into paid usage. This setting is disabled by default. Otherwise, a payment-verified account can incur pay-as-you-go charges after the allowance is exhausted or expires. The allowance does not cover batch calls, built-in tool fees, fine-tuning, or deployment, so this is not a blanket spending guarantee for every service.
Model Studio has its own eligibility rules. Its current new-user quota documentation limits free quotas to the Singapore region with International deployment scope. Do not apply those rules to every QwenCloud account or third-party provider.
For paid text requests, check the exact model’s input and output rates in QwenCloud pricing. Tokens are the units used to measure the text processed and generated; they are not a fixed number of words. A basic estimate is:
Cost = (input tokens ÷ 1,000,000 × input rate) + (output tokens ÷ 1,000,000 × output rate)
Apply the appropriate input-length tier and any relevant cache, quota, or tool charges. Reasoning tokens can add to billed output. Our Qwen API pricing and token-cost guide covers the calculation in more detail; use the provider’s current rates for the account you will actually call.
Get a Qwen API key and match your connection settings
- Open the QwenCloud console and sign in. Complete the account and payment requirements shown for the access you intend to use.
- Choose the appropriate workspace, then open API Keys. Create a pay-as-you-go key, give it a recognizable description, and copy it into secure storage. The full key is shown only when created.
- Check the API Host shown for that key. Confirm that the workspace permits the model you intend to call; a key’s existence alone does not establish every model permission.
These steps follow the official API key instructions and workspace permissions documentation. Keep the key, host, workspace, and model together as one configuration.
For the QwenCloud pay-as-you-go route documented in the quickstart, the OpenAI-compatible SDK base URL is:
https://maas.qwencloudapi.com/compatible-mode/v1
The complete HTTP endpoint for Chat Completions is:
https://maas.qwencloudapi.com/compatible-mode/v1/chat/completions
A direct HTTP client needs the complete endpoint. The OpenAI SDK needs the base URL because its chat method supplies the final path. Adding /chat/completions to the SDK’s base_url can produce the wrong request URL. Both forms are shown in the official connection examples.
The examples use DASHSCOPE_API_KEY, the environment-variable name used in QwenCloud’s configuration instructions. It must contain the key for this route, not an unrelated Model Studio or Token Plan key. In Python, the code passes the value explicitly to the client; the variable’s name does not select a provider automatically.
Make your first Qwen API request
QwenCloud supports both Chat Completions and Responses. Its text-generation guide recommends Responses for new integrations and Chat Completions for existing OpenAI-compatible code. The example here uses Chat Completions to make that familiar request format explicit; it is not a claim that the two APIs have identical parameters or features.
Use qwen3.7-plus for this example. It supports switching thinking off, which suits a tiny classification task. The request sets a 256-token completion budget rather than using a large reasoning allowance. See the thinking controls and Chat Completions parameter reference; max_completion_tokens is the current parameter used here instead of deprecated max_tokens.
Run a cURL example in Bash
Use Bash on macOS, Linux, or Windows Subsystem for Linux, with cURL 7.76.0 or later for the --fail-with-body option. This is not native PowerShell syntax. The Python alternative below avoids Bash-specific commands.
Save the following as qwen-first-call.sh. It asks for the key without displaying it or putting the literal secret in your shell command history. Running the file sends one real request and consumes available quota or incurs usage charges.
#!/usr/bin/env bash
set -euo pipefail
read -r -s -p "QwenCloud pay-as-you-go API key: " DASHSCOPE_API_KEY
printf '\n'
: "${DASHSCOPE_API_KEY:?No API key entered}"
export DASHSCOPE_API_KEY
curl --silent --show-error --fail-with-body \
--connect-timeout 10 --max-time 60 \
--request POST \
'https://maas.qwencloudapi.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--write-out '\nHTTP status: %{http_code}\n' \
--data '{
"model": "qwen3.7-plus",
"messages": [
{
"role": "system",
"content": "Classify the support ticket. Return only billing, technical, or account."
},
{
"role": "user",
"content": "I was charged twice for the same month."
}
],
"enable_thinking": false,
"max_completion_tokens": 256,
"stream": false
}'
Run it from the folder where you saved it:
bash qwen-first-call.sh
Paste your pay-as-you-go key at the prompt and press Enter; no characters appear while entering it. The script prints the response body and HTTP status. The connection and overall timeouts are example client settings, not a promised service response time.
Check the answer, completion status, and usage
In the documented Chat Completions response, read choices[0].message.content for the answer and choices[0].finish_reason for why generation ended. stop indicates a normal completion; length means a generation limit was reached. tool_calls indicates a tool-call handoff rather than a final answer.
Inspect usage.prompt_tokens, usage.completion_tokens, and usage.total_tokens for reported consumption. Keep the response id for troubleshooting. Do not assume HTTP 200 means the output is complete, correct, or safe to use automatically.
For this fictional ticket, billing is the appropriate category. That is the task’s expected interpretation, not a recorded model response. Reject empty answers, unexpected labels, and incomplete completions before routing a real ticket. A format check alone cannot prove that a classification is correct.
Use the Qwen API with the OpenAI Python SDK
The following alternative makes the same request and checks its output. Use Python 3.10 or later and install the current official OpenAI Python library, preferably inside your project’s virtual environment:
python -m pip install --upgrade openai
Save this as qwen_first_call.py. It reads DASHSCOPE_API_KEY when present and otherwise asks for the key privately. Check any existing value first: it must belong to the QwenCloud pay-as-you-go host used here.
import os
from getpass import getpass
from openai import APIConnectionError, APIStatusError, OpenAI
api_key = os.getenv("DASHSCOPE_API_KEY") or getpass("QwenCloud pay-as-you-go key: ")
if not api_key.strip():
raise SystemExit("No API key entered.")
try:
with OpenAI(
api_key=api_key,
base_url="https://maas.qwencloudapi.com/compatible-mode/v1",
timeout=60.0,
max_retries=0,
) as client:
result = client.chat.completions.create(
model="qwen3.7-plus",
messages=[
{
"role": "system",
"content": (
"Classify the support ticket. "
"Return only billing, technical, or account."
),
},
{
"role": "user",
"content": "I was charged twice for the same month.",
},
],
max_completion_tokens=256,
extra_body={"enable_thinking": False},
)
except APIStatusError as exc:
code = getattr(exc, "code", None) or "unspecified"
raise SystemExit(f"Request failed: HTTP {exc.status_code}; code={code}") from None
except APIConnectionError:
raise SystemExit("Connection failed: check the network, endpoint, and timeout.") from None
if not result.choices:
raise SystemExit("No response choice returned.")
choice = result.choices[0]
answer = (choice.message.content or "").strip()
print("Answer:", answer)
print("Finish reason:", choice.finish_reason)
print("Usage:", result.usage)
if choice.finish_reason != "stop" or answer not in {"billing", "technical", "account"}:
raise SystemExit("Review this result before using it: completion or format check failed.")
Run it with python qwen_first_call.py. Use python3 for both installation and execution when that is your interpreter’s command. Qwen-specific enable_thinking belongs in extra_body in this SDK, whereas cURL sends it directly in the JSON body, as shown in the official thinking examples.
This example deliberately disables automatic SDK retries. A connection failure does not, by itself, establish whether the server processed the request. Resolve configuration or billing errors before repeating calls, and introduce bounded retries only when your application can tolerate another attempt.
Using the OpenAI library does not send this request to OpenAI: the configured QwenCloud base URL determines the destination. Compatibility should be checked feature by feature. For differences beyond the first request, see our Qwen API and OpenAI API comparison.
Our longer Qwen API Python walkthrough covers the Alibaba Cloud Model Studio route, which needs its own regional and workspace configuration. For a server-side streaming application, use the Qwen API Node.js guide and retain the provider settings documented there.
Choose a model for your workload, not just its name
QwenCloud’s model-selection guide positions qwen3.7-plus as a balanced option, qwen3.8-max for more demanding reasoning and coding, and qwen3.8-flash for cost-sensitive work. These are provider recommendations, not independent performance results from this guide.
Start by measuring whether a model solves your actual task. For ticket classification, record incorrect categories, rejected formats, response time, and token usage on representative examples. A model that answers a demonstration correctly has not yet been validated for your support queue.
Copy the exact identifier from the current model catalog. Use a supported dated snapshot where offered when you need a controlled version change, and retest before switching models. Do not assume an undated name is a permanently fixed revision or that a dated snapshot makes outputs deterministic.
Check input modalities and output limits separately. A context window describes how much material a request can accommodate; it is not a promise that the model can generate an answer of that length. Request and token rate limits govern throughput instead, as explained in the rate-limit documentation.
Add streaming, structured output, or tools when needed
Stream answers without losing completion checks
For supported Chat Completions calls, set stream: true and read incremental response chunks. Request final usage with stream_options: {"include_usage": true}. QwenCloud’s streaming guide demonstrates the pattern with qwen3.7-plus. Assemble the answer, track how it finishes, and treat an interrupted stream as incomplete rather than saving whatever text arrived as a finished result.
Request structured data and validate its meaning
When the next step needs fields rather than prose, consult the structured-output documentation. Supported Qwen3.7-Plus models can use JSON Schema output. JSON object mode and schema-constrained output are different: valid JSON alone does not establish your required structure or correct field values. Our Qwen structured-output guide covers the implementation; your application must still validate business rules.
Separate tool requests from permission to act
With function calling, the model can propose a tool name and arguments. Your application decides whether the operation is allowed, runs the approved tool, and returns its result. A proposed refund function call is not authorization to issue a refund. Keep user permissions and validation outside the model’s decision.
Use the correct Responses request format
For a Responses integration, use the current QwenCloud Responses reference. Its endpoint ends in /compatible-mode/v1/responses, and its request format uses input rather than copying a Chat Completions body unchanged. Confirm supported tools and reasoning controls there; OpenAI compatibility does not mean every OpenAI feature is implemented.
Troubleshoot the first failed request
Read the provider’s error code as well as the HTTP status. The following checks are scoped to QwenCloud’s error documentation, not universal meanings for every service hosting Qwen.
| Error or symptom | What to check |
|---|---|
401 InvalidApiKey | Confirm the key belongs to this host and billing route. Check for whitespace, a deleted key, or a stale environment variable. |
403 Model.AccessDenied | Check the workspace’s permission to use the requested model. |
403 AccessDenied.Unpurchased | Review incomplete billing information and the activation requirements shown in the console. |
403 AllocationQuota.FreeTierOnly | Review the exhausted allowance and free-only setting. Do not disable protection unless you intend to allow paid usage. |
404 ModelNotFound | Verify the exact model identifier, service activation, and access for this account. |
400 Arrearage | Resolve the account’s overdue balance. Changing the prompt will not fix billing. |
429 throttling | Reduce request concurrency and token load. Check the applicable model and account limits before retrying. |
For rate-limit failures, queue work and use bounded exponential backoff rather than an immediate retry loop. QwenCloud’s account-level rate rules explain why creating another key does not create an independent allowance. For response truncation and more detailed diagnostics, see our Qwen API errors and finish-reason guide.
Keep credentials and production usage under control
Keep the provider key on your server, not in browser JavaScript, public WordPress code, screenshots, or a repository. Use environment variables or a secrets manager, separate development and production access, and revoke an exposed key rather than merely hiding it afterward. These practices align with QwenCloud’s data-security guidance.
For a public application, authenticate callers, limit requests per user, validate inputs, and reject unsafe tool actions before they execute. Avoid logging full authorization headers or confidential prompts. Before sending personal or business-sensitive data, check the terms and controls for the actual hosted API service; do not infer its retention or training policy from consumer-chat settings.
Monitor both API usage and the billing console. QwenCloud’s billing and cost-management documentation explains usage breakdowns and spending alerts. A notification is not, by itself, proof of an immediate hard spending cap; combine provider controls with application-level limits.
After one successful request, replace the fictional ticket with non-sensitive examples from your intended task. Confirm acceptable answers, output validation, and costs before increasing traffic or connecting tools that can change real data.
Last verified: October 5, 2026. Official documentation and the linked site guides were reviewed. The Bash and Python examples passed local syntax checks; no authenticated API request was executed, and this guide does not claim live response, latency, or billing measurements.
