Qwen API Key Setup: OpenAI-Compatible Endpoint and Python Example
Learn how to get a Qwen API key, copy the endpoint and model ID, run cURL and Python examples, compare Qwen API pricing, and avoid common setup errors.

A qwen api key search usually means the developer is already past the research stage. They do not need a broad introduction to Qwen. They need a working key, a base URL, a model ID, a minimal request, and enough pricing context to decide whether Qwen belongs in a production app.
This guide gives you that path. It shows how to get a Qwen API key through OurToken, which endpoint to call, which model IDs are currently exposed for Qwen 3.7 routes, how to run a cURL smoke test, how to call Qwen from Python through an OpenAI-compatible client, and how to estimate request cost from usage fields. The examples use the current Qwen API model directory, the Qwen3.7 Plus API page, and the Qwen3.7 Max API page as the source of truth for route names, endpoint shape, and pricing.
Here is the short version:
Base URL: https://api.ourtoken.ai/v1
Full endpoint: https://api.ourtoken.ai/v1/chat/completions
Default model: qwen3.7-plus
Higher route: qwen3.7-max
Auth header: Authorization: Bearer YOUR_API_KEY
Use qwen3.7-plus for the first request because it is the balanced Qwen route and has lower unit cost. Use qwen3.7-max when you want to compare a higher-capability Qwen route for reasoning, coding, multilingual chat, and benchmark validation.
Verification status: This article is documentation-verified against the live OurToken Qwen pages on 2026-07-31. The examples were not executed with a private API key in this draft. Run the smoke test with your own credential before routing production traffic.
How to Get a Qwen API Key
A Qwen API key is the credential your server uses to authenticate requests. It is not the model ID, not the provider name, and not the endpoint URL. Keep those settings separate, because most setup failures come from mixing them together.
Create or manage the credential from the OurToken API Keys page. The page may require sign-in before key management appears. After creating a key, store it as a server-side secret or local environment variable.
On macOS or Linux:
export OURTOKEN_API_KEY="paste-your-key-locally"
On Windows PowerShell:
$env:OURTOKEN_API_KEY = "paste-your-key-locally"
Do not put the key in frontend JavaScript, a public GitHub repository, a mobile app bundle, a browser screenshot, or a notebook you plan to share. A leaked API key is a billing and abuse problem, not just a style issue.
For team use, create separate keys for local development, staging, and production. That separation makes it much easier to rotate a key after a leak, identify which environment is creating unexpected traffic, and shut down a test integration without touching production. If your application has multiple features, add feature-level labels in your own logging layer, because the API key alone will not tell you whether spend came from chat, extraction, summarization, or an internal agent workflow.
Qwen API endpoint and model ID
The OurToken Qwen route uses an OpenAI-compatible Chat Completions endpoint. If you call the route with raw HTTP, use the full endpoint. If you use the OpenAI SDK, pass only the base URL and let the SDK append /chat/completions when you call client.chat.completions.create.
| Setting | Value | Where to use it |
|---|---|---|
| SDK base URL | https://api.ourtoken.ai/v1 | OpenAI-compatible SDK clients |
| Full API endpoint | https://api.ourtoken.ai/v1/chat/completions | cURL, Postman, raw HTTP |
| Balanced model ID | qwen3.7-plus | Default production evaluation |
| Higher-capability model ID | qwen3.7-max | Reasoning, coding, benchmark comparison |
| Required request fields | model, messages, max_tokens | Minimal Chat Completions request |
| Auth header | Authorization: Bearer YOUR_API_KEY | Every API call |
The exact punctuation matters. qwen3.7-plus and qwen3.7-max are callable model IDs on the OurToken pages. Do not replace them with display names such as Qwen 3.7 Plus, catalog-style strings such as qwen/qwen3.7-plus, or guessed variants such as qwen-3.7-plus.
OpenAI's current Chat Completions API reference is a useful reference for the general request contract: a model value, a messages array, and optional generation parameters. OurToken's Qwen pages define the route-specific values you should actually send.
Choosing Plus or Max first
For a first Qwen API key setup, start with qwen3.7-plus. It is the balanced route and keeps the smoke test inexpensive. Move to qwen3.7-max only after you have a baseline output and want to test whether the higher route improves your workload.
| Route | Best first use | Current OurToken positioning |
|---|---|---|
qwen3.7-plus | Production app evaluation, chat, coding, multilingual tasks | Balanced Qwen 3.7 option |
qwen3.7-max | Harder reasoning, coding, benchmark validation | Higher-capability Qwen 3.7 option |
This choice is practical SEO and practical engineering at the same time. Many users search qwen api key because they want a first request, not a theoretical route comparison. Give them the cheapest reliable smoke test first, then show the upgrade path.
Qwen cURL and Python API Examples
The first test should be boring. It should prove the key, endpoint, model ID, and request body work together. Do not test streaming, tools, JSON schema output, retries, and long context in the first request. Those are second-step checks.
Qwen API cURL example
Use cURL when you want to isolate the API from your SDK, framework, proxy, or application code. This request calls the Qwen3.7 Plus route through the OurToken Chat Completions endpoint:
curl https://api.ourtoken.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OURTOKEN_API_KEY" \
-d '{
"model": "qwen3.7-plus",
"messages": [
{
"role": "system",
"content": "You are a concise API testing assistant."
},
{
"role": "user",
"content": "Reply with one sentence explaining what a Qwen API key does."
}
],
"max_tokens": 120
}'
Expected result shape:
{
"id": "chatcmpl_...",
"object": "chat.completion",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "A Qwen API key authenticates your application so it can call Qwen model routes through the API."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 32,
"completion_tokens": 22,
"total_tokens": 54
}
}
The exact IDs, text, and token counts will vary. The important parts are choices[0].message.content for output and usage.prompt_tokens, usage.completion_tokens, and usage.total_tokens for cost reporting.
If you want to test the higher route, change only the model ID:
{
"model": "qwen3.7-max"
}
Do not change the model and the prompt at the same time. A clean comparison keeps the request body stable so you can tell whether the route itself changed quality, latency, or cost.
Qwen Python API example
Install the OpenAI Python SDK:
pip install openai
Then call the Qwen route through the OpenAI-compatible base URL:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["OURTOKEN_API_KEY"],
base_url="https://api.ourtoken.ai/v1",
)
response = client.chat.completions.create(
model="qwen3.7-plus",
messages=[
{
"role": "system",
"content": "You are a concise API testing assistant.",
},
{
"role": "user",
"content": "Give me three practical use cases for Qwen in a SaaS app.",
},
],
max_tokens=240,
)
print(response.choices[0].message.content)
print(response.usage)
The subtle but important detail: base_url is https://api.ourtoken.ai/v1, not https://api.ourtoken.ai/v1/chat/completions. The SDK method appends the operation path for you. Passing the full endpoint as base_url commonly creates a doubled path and a confusing 404.
Production-safe wrapper
Once the plain call works, put the model ID and endpoint in one configuration object. That makes it easier to switch between qwen3.7-plus and qwen3.7-max without hunting through application code.
import os
from dataclasses import dataclass
from openai import OpenAI
@dataclass(frozen=True)
class QwenRoute:
model: str
input_per_million: float
output_per_million: float
cache_read_per_million: float
cache_write_per_million: float
QWEN_PLUS = QwenRoute(
model="qwen3.7-plus",
input_per_million=0.1650,
output_per_million=0.6610,
cache_read_per_million=0.0170,
cache_write_per_million=0.2060,
)
QWEN_MAX = QwenRoute(
model="qwen3.7-max",
input_per_million=1.0000,
output_per_million=2.9700,
cache_read_per_million=0.1980,
cache_write_per_million=1.2380,
)
client = OpenAI(
api_key=os.environ["OURTOKEN_API_KEY"],
base_url="https://api.ourtoken.ai/v1",
)
def ask_qwen(prompt: str, route: QwenRoute = QWEN_PLUS) -> str:
completion = client.chat.completions.create(
model=route.model,
messages=[
{"role": "system", "content": "Answer clearly and briefly."},
{"role": "user", "content": prompt},
],
max_tokens=300,
)
return completion.choices[0].message.content or ""
print(ask_qwen("Summarize the benefits of an OpenAI-compatible API."))
This wrapper is intentionally small. It does not hide errors, retry forever, or create a model router before you know your baseline works. Production logic can come after the first reliable request.
After the wrapper is live, add one operational feature at a time: timeout settings, request IDs, structured error logs, and a single retry for safe transient failures. Keep application prompts outside the wrapper so product teams can improve instructions without changing transport code. Keep route prices in configuration so finance or platform engineers can update cost estimates when the model page changes.
Qwen API Pricing and Cost Planning
A Qwen API key can work perfectly and still create a budget problem if you choose the wrong route for the workload. Pricing matters most when an app has long prompts, repeated context, or high output volume.
At the time this article was prepared, the live OurToken Qwen pages listed these route-level prices:
| Token category | Qwen3.7 Plus on OurToken | Qwen3.7 Max on OurToken |
|---|---|---|
| Input | $0.1650 / 1M tokens | $1.0000 / 1M tokens |
| Output | $0.6610 / 1M tokens | $2.9700 / 1M tokens |
| Cached input | $0.0170 / 1M tokens | $0.1980 / 1M tokens |
| Cache writes | $0.2060 / 1M tokens | $1.2380 / 1M tokens |
| Pricing note | 60% of official reference on page | 60% of official reference on page |
Always verify the current numbers on the live Qwen3.7 Plus API pricing page and Qwen3.7 Max API pricing page before publishing a cost calculator or committing a budget. Model prices can change, and cached-token behavior should be measured on your own workload.
Cost calculation from usage
For a standard Chat Completions response without cache details, the basic calculation is:
input_cost = prompt_tokens / 1_000_000 * input_price
output_cost = completion_tokens / 1_000_000 * output_price
total_cost = input_cost + output_cost
Python helper:
def estimate_chat_cost_usd(
usage: dict,
*,
input_per_million: float,
output_per_million: float,
) -> dict[str, float]:
prompt_tokens = int(usage.get("prompt_tokens", 0) or 0)
completion_tokens = int(usage.get("completion_tokens", 0) or 0)
input_cost = prompt_tokens / 1_000_000 * input_per_million
output_cost = completion_tokens / 1_000_000 * output_per_million
return {
"input_cost": input_cost,
"output_cost": output_cost,
"total_cost": input_cost + output_cost,
}
example_usage = {"prompt_tokens": 12000, "completion_tokens": 800}
print(
estimate_chat_cost_usd(
example_usage,
input_per_million=0.1650,
output_per_million=0.6610,
)
)
For qwen3.7-plus, a request with 12,000 input tokens and 800 output tokens costs about:
Input: 12,000 / 1,000,000 * $0.1650 = $0.00198
Output: 800 / 1,000,000 * $0.6610 = $0.0005288
Total: about $0.0025088
For qwen3.7-max, the same token shape costs about:
Input: 12,000 / 1,000,000 * $1.0000 = $0.01200
Output: 800 / 1,000,000 * $2.9700 = $0.002376
Total: about $0.014376
That does not mean Max is bad. It means Max should earn its higher unit cost with better answer quality, higher task success, fewer retries, or fewer human escalations. For many production workflows, the right approach is to test Plus as the default and reserve Max for prompts that fail quality checks.
Cached input and repeated prompts
The Qwen pages list cached input and cache write prices. That matters for apps that repeat a long system prompt, tool definitions, policy text, or retrieval instructions across many requests.
Do not say prompt caching reduces token count unless your application actually sends fewer tokens. In many cases, cached input reduces the price applied to repeated input tokens. The model still receives the context; the repeated prefix is simply billed differently when cache behavior applies.
If usage includes prompt_tokens_details.cached_tokens, treat cached tokens as a subset of prompt_tokens, not extra tokens to add on top:
def estimate_cached_chat_cost_usd(
usage: dict,
*,
input_per_million: float,
output_per_million: float,
cache_read_per_million: float,
) -> dict[str, float]:
prompt_tokens = int(usage.get("prompt_tokens", 0) or 0)
completion_tokens = int(usage.get("completion_tokens", 0) or 0)
details = usage.get("prompt_tokens_details") or {}
cached_tokens = int(details.get("cached_tokens", 0) or 0)
uncached_tokens = max(prompt_tokens - cached_tokens, 0)
input_cost = uncached_tokens / 1_000_000 * input_per_million
cached_cost = cached_tokens / 1_000_000 * cache_read_per_million
output_cost = completion_tokens / 1_000_000 * output_per_million
return {
"uncached_input_cost": input_cost,
"cached_input_cost": cached_cost,
"output_cost": output_cost,
"total_cost": input_cost + cached_cost + output_cost,
}
For deeper implementation details on repeated prompt prefixes, read the existing OpenAI-compatible prompt caching guide. It explains where cached input usually helps and where it only makes dashboards look mysterious.
Production Setup Checklist
The fastest way to ship a reliable Qwen integration is to keep the first version plain, observable, and easy to roll back. A Qwen API key is only one part of the system. The route also needs clean configuration, error handling, usage logging, and model comparison.
Application server
-> reads OURTOKEN_API_KEY from secret storage
-> selects qwen3.7-plus or qwen3.7-max from config
-> calls https://api.ourtoken.ai/v1/chat/completions
-> validates choices[0].message.content
-> records prompt_tokens and completion_tokens
-> estimates request cost
-> retries only safe transient errors
-> escalates repeated failures to fallback logic
This architecture keeps the API key out of the browser and keeps model routing inside server-side code. It also gives you the data needed to decide whether Qwen3.7 Max is worth using for specific prompts.
Common setup errors
| Error | Symptom | Fix |
|---|---|---|
| Full endpoint used as SDK base URL | 404 or doubled path | Use https://api.ourtoken.ai/v1 as base_url |
| Display name used as model ID | 400 or model not found | Use qwen3.7-plus or qwen3.7-max |
| Missing Bearer prefix | 401 unauthorized | Send Authorization: Bearer YOUR_API_KEY |
| Key stored in client code | Security exposure | Move calls to a server route |
| Max route used for every request | Higher bill than needed | Start with Plus and escalate selectively |
| No usage logging | Cannot debug cost | Store token counts per route and feature |
If you plan to use tools, start from a working plain chat request, then add tool definitions one at a time. The OpenAI-compatible tool calling guide is the relevant next step because tool schemas can change request size, output shape, latency, and model behavior.
Model comparison workflow
A fair Qwen Plus vs Max comparison needs a fixed prompt set. Use 30 to 100 real prompts from your workload: support tickets, code edits, extraction tasks, retrieval questions, or multilingual conversations. Run the same prompt set against both routes and score the outputs before changing production traffic.
| Metric | Why it matters |
|---|---|
| Task success | Measures whether the answer solves the real job |
| Retry rate | A cheaper model can become expensive if it needs retries |
| Human escalation rate | Important for support and operations workflows |
| Prompt tokens | Drives input cost and cache strategy |
| Completion tokens | Drives output cost |
| Latency | Affects chat and agent UX |
| Parse success | Matters for JSON or tool workflows |
Keep the first scoring rubric simple. A three-level score such as pass, partial, and fail is often enough to decide whether Plus should be the default route and Max should be reserved for hard prompts.
Conclusion and FAQ
A Qwen API key setup should be direct: get the key, use the correct base URL, call /chat/completions, choose a valid model ID, run a small cURL test, then move to Python. For most teams, qwen3.7-plus is the better first route because it keeps setup and evaluation costs low. Use qwen3.7-max when the prompt needs a stronger Qwen route and you can measure the quality gain.
When you are ready to test, open the Qwen model directory, copy the current route details, create a credential from OurToken API Keys, and keep the OurToken configuration docs nearby for client setup patterns. The conversion path is intentionally short because API key readers are already close to action.
FAQ
How do I get a Qwen API key?
Create an OurToken account, open the API key page, and create a server-side key. Store it as an environment variable such as OURTOKEN_API_KEY and send it with Authorization: Bearer YOUR_API_KEY.
What is the Qwen API endpoint?
For the OurToken Qwen route, the full endpoint is https://api.ourtoken.ai/v1/chat/completions. SDK clients should use https://api.ourtoken.ai/v1 as the base URL.
What Qwen model ID should I use?
Use qwen3.7-plus for the balanced route and qwen3.7-max for the higher-capability route. Copy the model ID exactly, including the dot between 3 and 7.
Can I use Qwen with the OpenAI Python SDK?
Yes. Configure the OpenAI SDK with your OurToken API key and base_url="https://api.ourtoken.ai/v1", then call client.chat.completions.create with a Qwen model ID.
Is there a Qwen API key free tier?
Do not assume a permanent free tier unless the live account page explicitly shows one for your account. Treat any credit, trial, or promotion as account-specific and verify it before writing production budget assumptions.
How should I compare Qwen API pricing?
Compare route-level input, output, cached input, and cache write prices. Then measure your own prompt and completion token counts. Unit price alone is not enough if one route needs fewer retries or produces better first-pass answers.