Make your first API call to Qwen
Alibaba Cloud Model Studio supports API calls to models through OpenAI-compatible interfaces and the DashScope SDK.
Note
- If you are familiar with model API calls, go directly to the Qwen API reference.
- If you are not familiar with programming, try Chatbox to interact with Qwen models through a graphical interface.
To call the Qwen API:
- Get an API key
- Set up your local development environment
- Call the Qwen API
Account setup
-
Create an account: If you do not have an Alibaba Cloud account, create one.
If you encounter issues, see Register an Alibaba Cloud account.
-
Activate Model Studio: Use your Alibaba Cloud account to go to Alibaba Cloud Model Studio. Read and accept the Terms of Service to activate the service. If no Terms of Service dialog appears, the service is already activated.
If you see the message “You have not completed identity verification” when activating the service, complete identity verification first.
-
Get an API key: Go to the API Key page and click Create API key. Then use the API key to call models.
You do not need to select a model when you create an API key. Specify the model to call through the
modelparameter in the request body, for example,model="qwen-plus". For supported models, see Model list. To limit the models that an API key can call, select the Custom permission when you create the key and turn on the Model access scope switch. The key can then call only the models that you selected. -
Get your workspace ID: When calling models in the China (Beijing), Singapore, Japan (Tokyo), , Germany (Frankfurt), or China (Hong Kong) region, you need to include the workspace ID (WorkspaceId) in the Base URL. You can find it on the Workspace Management page.
Set your API key as an environment variable
Store your API key in an environment variable to avoid hardcoding credentials and reduce security risks.
Steps
Linux
Permanent
To make the API key available in all new sessions for the current user, set it as a permanent environment variable.
- Run the following command to append the environment variable setting to the
~/.bashrcfile.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.bashrc
Alternatively, you can manually edit the ~/.bashrc file.
Run the following command to open the ~/.bashrc file.
nano ~/.bashrc Add the following content to the configuration file.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file. 2. Run the following command to apply the changes.
source ~/.bashrc
3. Open a new terminal window and run the following command to verify that the environment variable is set.
echo $DASHSCOPE_API_KEY
Temporary
To use the environment variable only for the current session, set it as a temporary environment variable.
- Run the following command.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
-
Run the following command to verify that the environment variable is set.
echo $DASHSCOPE_API_KEY
macOS
Permanent
To make the API key available in all new sessions for the current user, set it as a permanent environment variable.
-
Run the following command in your terminal to check your default shell type.
echo $SHELL -
Proceed based on your default shell type.
Zsh- Run the following command to append the environment variable setting to the
~/.zshrcfile.
- Run the following command to append the environment variable setting to the
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.zshrc
Alternatively, you can manually edit the ~/.zshrc file.
Run the following command to open the shell configuration file.
nano ~/.zshrc Add the following content to the configuration file.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file. 2. Run the following command to apply the changes.
source ~/.zshrc
3. Open a new terminal window and run the following command to verify that the environment variable is set.
echo $DASHSCOPE_API_KEY
- Run the following command to append the environment variable setting to the
~/.bash_profilefile.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.bash_profile
Alternatively, you can manually edit the ~/.bash_profile file.
Run the following command to open the shell configuration file.
nano ~/.bash_profile Add the following content to the configuration file.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
In the nano editor, press Ctrl+X, then Y, and then Enter to save and close the file. 2. Run the following command to apply the changes.
source ~/.bash_profile
3. Open a new terminal window and run the following command to verify that the environment variable is set.
echo $DASHSCOPE_API_KEY
Temporary
To use the environment variable only for the current session, set it as a temporary environment variable.
The following command applies to both Zsh and Bash.
- Run the following command.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
-
Run the following command to verify that the environment variable is set.
echo $DASHSCOPE_API_KEY
Windows
In Windows, you can configure an environment variable by using System Properties, Command Prompt, or Windows PowerShell.
System Properties
- Environment variables configured this way are permanent.
- You need administrator permissions to modify system environment variables.
- Changes to environment variables do not affect running applications, including Command Prompt windows and IDEs. You must restart these applications or open a new command-line session to apply the changes.
-
On the Windows desktop, press
Win+Q, search for Edit the system environment variables in the search box, and click the search result to open the System Properties window. -
In the System Properties window, click Environment Variable, and then in the System variables section, click Create. For Variable Name, enter
DASHSCOPE_API_KEY, and for Variable value, enter your DashScope API Key. -
Click OK on all three open windows to save the changes and close them.
-
Open a new Command Prompt or Windows PowerShell window and run the appropriate command to verify that the environment variable is set.
-
In Command Prompt:
echo %DASHSCOPE_API_KEY%
-
Microsoft Windows [Version 10.0.19045.5371]
(c) Microsoft Corporation. All rights reserved.
C:\Windows\system32>echo %DASHSCOPE_API_KEY%
sk-ee166797fe40xxx
C:\Windows\system32>
-
In Windows PowerShell:
echo $env:DASHSCOPE_API_KEY
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS C:\Windows\system32> echo $env:DASHSCOPE_API_KEY
sk-ee166797fe40xxx
PS C:\Windows\system32>
Command Prompt
PermanentTo make the API key environment variable available in all new sessions for the current user, follow these steps.
- Run the following command in Command Prompt.
REM Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
setx DASHSCOPE_API_KEY "YOUR_DASHSCOPE_API_KEY"
-
Open a new Command Prompt window for the change to take effect.
-
In the new Command Prompt window, run the following command to verify that the environment variable is set.
echo %DASHSCOPE_API_KEY%
To use the environment variable only in the current session, run the following command in Command Prompt.
REM Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
set DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY
You can run the following command in the same session to verify that the environment variable is set.
echo %DASHSCOPE_API_KEY%
Windows PowerShell
PermanentTo make the API key environment variable available in all new sessions for the current user, follow these steps.
- Run the following command in Windows PowerShell.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
[Environment]::SetEnvironmentVariable("DASHSCOPE_API_KEY", "YOUR_DASHSCOPE_API_KEY", [EnvironmentVariableTarget]::User)
-
Open a new Windows PowerShell window for the change to take effect.
-
In the new Windows PowerShell window, run the following command to verify that the environment variable is set.
echo $env:DASHSCOPE_API_KEY
Temporary
If you want to use the environment variable only in the current session, you can run the following command in PowerShell.
# Replace YOUR_DASHSCOPE_API_KEY with your Model Studio API key
$env:DASHSCOPE_API_KEY = "YOUR_DASHSCOPE_API_KEY"
You can run the following command in the same session to verify that the environment variable is set.
echo $env:DASHSCOPE_API_KEY
Choose a development language
Select a language or tool to call model APIs.
Python
Step 1: Set up Python
Check your Python version
Python 3.8 or later is required. For installation instructions, see Install Python.
Run this command to check whether Python and pip are installed:
python -V
pip --version
For example, on Windows Command Prompt:
C:\Users\Administrator>python -V
Python 3.13.2
C:\Users\Administrator>pip --version
pip 24.3.1 from C:\Users\Administrator\AppData\Local\Programs\Python\Python313\Lib\site-packages\pip (python 3.13)
FAQ
Q: The commands python -V and pip --version return errors:
'python' is not recognized as an internal or external command, operable program or batch file.'pip' is not recognized as an internal or external command, operable program or batch file.-bash: python: command not found-bash: pip: command not found
Try these solutions:
Windows
-
Confirm that you installed Python by following Install Python, and added python.exe to the PATH environment variable.
When installing Python 3.13.2, select Add python.exe to PATH at the bottom of the installer to add Python to the system environment variables, then click Install Now to complete the installation.
-
If Python and PATH are correctly configured but the error persists, close your current terminal and open a new one.
Linux and macOS
-
Confirm that you installed Python by following Install Python.
-
If Python is installed but the error persists, run
which python pipto check whetherpythonandpipexist in your system.- If this result appears, close the current terminal window, open a new terminal window, and try again.
/usr/bin/python
/usr/bin/pip
- If this result is returned, run the
which python3 pip3query again.
/usr/bin/which: no python in (/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin)
/usr/bin/which: no pip in (/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin)
If the returned result is shown, use python3 -V and pip3 --version to check the version.
/usr/bin/python3
/usr/bin/pip3
Set up a virtual environment (optional)
If Python is already installed, you can create a virtual environment to install the OpenAI Python SDK or the DashScope Python SDK and avoid dependency conflicts.
-
Create a virtual environment
Create a virtual environment named .venv:
# If this fails, replace python with python3
python -m venv .venv
-
Activate the virtual environment
On Windows, activate the virtual environment:
.venv\Scripts\activate
On macOS or Linux, run:
source .venv/bin/activate
Install the DashScope Python SDK or OpenAI Python SDK
You can call models on Model Studio using the DashScope Python SDK (recommended) or the OpenAI Python SDK.
Install the DashScope Python SDK
Install or upgrade the DashScope Python SDK:
# If this fails, replace pip with pip3
pip install -U dashscope
Look for Successfully installed ... dashscope-x.x.x to confirm installation.
Install the OpenAI Python SDK
Install or upgrade the OpenAI Python SDK:
# If this fails, replace pip with pip3
pip install -U openai
Look for Successfully installed ... openai-x.x.x to confirm installation.
Step 2: Call the API
DashScope Python SDK
With Python and the DashScope Python SDK installed, send your first API request.
- Create a file named
hello_qwen.py. - Copy this code into
hello_qwen.pyand save it.
import os
from dashscope import MultiModalConversation
import dashscope
# The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'
messages = [
{'role': 'system', 'content': [{'text': 'You are a helpful assistant.'}]},
{'role': 'user', 'content': [{'text': 'Who are you?'}]}
]
response = MultiModalConversation.call(
# If the environment variable is not configured, replace with: api_key = "sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3.8-max", # Model list: https://help.aliyun.com/model-studio/getting-started/models
messages=messages
)
if response.status_code == 200:
print(response.output.choices[0].message.content[0]["text"])
else:
print(f"HTTP status code: {response.status_code}")
print(f"Error code: {response.code}")
print(f"Error message: {response.message}")
print("See: https://help.aliyun.com/model-studio/developer-reference/error-code")
-
Run
python hello_qwen.pyorpython3 hello_qwen.pyfrom the command line.NoteThe command in this example must be executed from the directory containing the Python file. To run it from elsewhere, specify the full path.
The output is:
I am a large-scale language model from Alibaba Cloud. My name is Qwen.
OpenAI Python SDK
With Python and the OpenAI Python SDK installed, send your first API request.
- Create a file named
hello_qwen.py. - Copy this code into
hello_qwen.pyand save it.
import os
from openai import OpenAI
try:
client = OpenAI(
# If the environment variable is not configured, replace with: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-max", # Model list: https://help.aliyun.com/model-studio/getting-started/models
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'}
]
)
print(completion.choices[0].message.content)
except Exception as e:
print(f"Error message: {e}")
print("See: https://help.aliyun.com/model-studio/developer-reference/error-code")
-
Run
python hello_qwen.pyorpython3 hello_qwen.pyfrom the command line.If you see
No such file or directory, specify the full path to the file.The output is:
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.
Node.js
Step 1: Set up your Node.js environment
Check your Node.js installation
Check whether Node.js and npm are installed:
node -v
npm -v
For example, on Windows Command Prompt:
C:\Users\Administrator>node -v
v22.14.0
C:\Users\Administrator>npm -v
10.9.2
This prints your current Node.js version. If Node.js is not installed, download it from the Node.js official website.
Install the model calling SDK
Run this command in your terminal:
npm install --save openai
# Or
yarn add openai
NoteIf installation fails, configure a registry mirror:
npm config set registry https://registry.npmmirror.com/
After configuring the mirror, rerun the SDK installation command.
Look for added xx package in xxs to confirm installation. Check version: npm list openai.
Step 2: Call the model API
- Create a file named
hello_qwen.mjs. - Copy this code into the file.
import OpenAI from "openai";
try {
const openai = new OpenAI(
{
// If the environment variable is not configured, replace with: apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-max", // Model list: https://help.aliyun.com/model-studio/getting-started/models
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Who are you?" }
],
});
console.log(completion.choices[0].message.content);
} catch (error) {
console.log(`Error message: ${error}`);
console.log("See: https://help.aliyun.com/model-studio/developer-reference/error-code");
}
- Run this command to send an API request.
node hello_qwen.mjs
Note
- Run this command from the directory containing
hello_qwen.mjs. To run it from any location, specify the full path to the file. - Ensure the SDK is installed in the same directory as
hello_qwen.mjs. If they are in different directories, you will seeCannot find package 'openai' imported from xxx.
After successful execution, the output is:
PS D:\node_project> node hello_qwen.mjs
(node:25072) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
我是来自阿里云的语言模型,我叫通义千问。
PS D:\node_project>
Java
Step 1: Set up your Java environment
Check your Java version
Run this command in your terminal:
java -version
# (Optional) If you use Maven to manage and build Java projects, ensure Maven is installed
mvn --version
For example, on Windows Command Prompt:
C:\Users\Administrator>java --version
java 23.0.2 2025-01-21
Java(TM) SE Runtime Environment (build 23.0.2+7-58)
Java HotSpot(TM) 64-Bit Server VM (build 23.0.2+7-58, mixed mode, sharing)
C:\Users\Administrator>mvn --version
Apache Maven 3.9.9 (8e8579a9e76f7d015ee5ec7bfcdc97d260186937)
Maven home: C:\Program Files\apache-maven-3.9.9
Java version: 23.0.2
Java 8 or later is required for the DashScope Java SDK. For example, openjdk version "16.0.1" 2021-04-20 means Java 16. If Java is not installed or the version is below Java 8, download and install it from Java downloads.
Install the model calling SDK
Install the DashScope Java SDK. For the latest version, see DashScope Java SDK. Add this dependency, replacing the-latest-version with the latest version number.
XML
- Open your Maven project's
pom.xmlfile. - Add this dependency to the
<dependencies>tag:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<!-- Replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<version>the-latest-version</version>
</dependency>
- Save the
pom.xmlfile. - Run a Maven command such as
mvn compileormvn clean installto update dependencies. Maven will automatically download and add the DashScope Java SDK to your project.
For example, in IntelliJ IDEA on Windows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<!-- Replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<version>2.18.2</version>
</dependency>
</dependencies>
</project>
~\Desktop\test_project
mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------------< org.example:test_project >----------------------
[INFO] Building test_project 1.0-SNAPSHOT
[INFO] from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ test_project ---
[INFO] skip non existing resourceDirectory C:\Users\Administrator\Desktop\test_project\src\main\resources
[INFO]
[INFO] --- compiler:3.13.0:compile (default-compile) @ test_project ---
[INFO] Nothing to compile - all classes are up to date.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.627 s
[INFO] Finished at: 2025-02-17T13:15:30+08:00
[INFO] ------------------------------------------------------------------------
Gradle
- Open your Gradle project's
build.gradlefile. - Add this dependency to the
dependenciesblock:
dependencies {
// Replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'the-latest-version'
}
- Save the
build.gradlefile. - In your terminal, navigate to your project root directory and run this Gradle command to update dependencies. It will automatically download and add the DashScope Java SDK to your project.
./gradlew build --refresh-dependencies
For example, in IntelliJ IDEA on Windows:
Complete build.gradle file example:
group = 'org.example'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.apache.groovy:groovy:4.0.14'
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '2.18.2'
}
test {
useJUnitPlatform()
}
After running the build command, the terminal output is:
~/Desktop/test_project
./gradlew build --refresh-dependencies
Welcome to Gradle 8.10!
Here are the highlights of this release:
- Support for Java 23
- Faster configuration cache
- Better configuration cache reports
For more details see https://docs.gradle.org/8.10/release-notes.html
BUILD SUCCESSFUL in 7m 51s
2 actionable tasks: 2 executed
Step 2: Call the API
Run this code to call the model API.
import java.util.Arrays;
import java.util.Collections;
import java.lang.System;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public static MultiModalConversationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
MultiModalConversation conv = new MultiModalConversation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1");
MultiModalMessage systemMsg = MultiModalMessage.builder()
.role(Role.SYSTEM.getValue())
.content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
.build();
MultiModalMessage userMsg = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(Collections.singletonMap("text", "Who are you?")))
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// If the environment variable is not configured, replace with: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Model list: https://help.aliyun.com/model-studio/getting-started/models
.model("qwen3.8-max")
.messages(Arrays.asList(systemMsg, userMsg))
.build();
return conv.call(param);
}
public static void main(String[] args) {
try {
MultiModalConversationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
System.out.println("See: https://help.aliyun.com/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
The output is:
I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.
curl
Call models on Model Studio using OpenAI-compatible or DashScope HTTP endpoints. For supported models, see Model list.
NoteIf DASHSCOPE_API_KEY is not set, replace -H "Authorization: Bearer $DASHSCOPE_API_KEY" with -H "Authorization: Bearer sk-xxx".
OpenAI-compatible HTTP
Send the API request:
Windows
Run this command in Command Prompt:
curl -X POST "https://{WorkspaceId}.cn-beijing.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 helpful assistant.\"
},
{
\"role\": \"user\",
\"content\": \"Who are you?\"
}
]
}"
Linux and macOS
Run this command in Terminal:
curl -X POST https://{WorkspaceId}.cn-beijing.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 helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
}'
After sending the API request, you receive this response:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "I am a large-scale language model from Alibaba Cloud. My name is Qwen."
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 22,
"completion_tokens": 16,
"total_tokens": 38
},
"created": 1728353155,
"system_fingerprint": null,
"model": "qwen3.8-max",
"id": "chatcmpl-39799876-eda8-9527-9e14-2214d641cf9a"
}
DashScope HTTP
Send the API request:
Windows
Run this command in Command Prompt:
curl -X POST "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" ^
-H "Authorization: Bearer %DASHSCOPE_API_KEY%" ^
-H "Content-Type: application/json" ^
-d "{
\"model\": \"qwen3.8-max\",
\"input\": {
\"messages\": [
{
\"role\": \"system\",
\"content\": [{\"text\": \"You are a helpful assistant.\"}]
},
{
\"role\": \"user\",
\"content\": [{\"text\": \"Who are you?\"}]
}
]
},
\"parameters\": {
\"result_format\": \"message\"
}
}"
Linux and macOS
Run this command in Terminal:
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input":{
"messages":[
{
"role": "system",
"content": [{"text": "You are a helpful assistant."}]
},
{
"role": "user",
"content": [{"text": "Who are you?"}]
}
]
},
"parameters": {
"result_format":"message"
}
}'
After sending the API request, you receive this response:
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [{"text": "I am a large-scale language model from Alibaba Cloud. My name is Qwen."}]
}
}
]
},
"usage": {
"total_tokens": 38,
"output_tokens": 16,
"input_tokens": 22
},
"request_id": "87f776d7-3c82-9d39-b238-d1ad38c9b6a9"
}
Other languages
Call the model APIpackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type RequestBody struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
}
func main() {
// Create an HTTP client
client := &http.Client{}
// Build the request body
requestBody := RequestBody{
// Model list: https://help.aliyun.com/model-studio/getting-started/models
Model: "qwen3.8-max",
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "Who are you?",
},
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
req, err := http.NewRequest("POST", "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// If the environment variable is not configured, replace with: apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the request
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Read the response body
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// Print the response
fmt.Printf("%s\n", bodyText)
}
<?php
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
$url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// If the environment variable is not configured, replace with: $apiKey = "sk-xxx"
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set request headers
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// Set request body
$data = [
// Model list: https://help.aliyun.com/model-studio/getting-started/models
"model" => "qwen3.8-max",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
];
// Initialize a cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute the cURL session
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Close the cURL resource
curl_close($ch);
// Output the response
echo $response;
?>
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// If the environment variable is not configured, replace with: string? apiKey = "sk-xxx"
// Singapore and China (Beijing) API keys differ. Get your API key: https://help.aliyun.com/model-studio/get-api-key
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key not set. Make sure the 'DASHSCOPE_API_KEY' environment variable is set.");
return;
}
// The following base URL is for the China (Beijing) region. URLs vary by region. Replace {WorkspaceId} with your workspace ID.
string url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
// Model list: https://help.aliyun.com/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen3.8-max"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
}";
// Send the request and get the response
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Output the result
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// Set request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send the request and get the response
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Handle the response
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
API reference
- For the input and output parameters, see Qwen API reference.
- For other models, see Model list.
FAQ
How do I buy tokens after my Free quota runs out?
A: Go to Expenses and Costs. Ensure there are no overdue payments before calling Qwen models.
Calls to Qwen models are billed automatically. Bills are generated by the minute, with each entry detailing the charges for that minute. View usage details in Bill details.
How do I fix theModel.AccessDeniederror after calling the model API?
A: This error occurs because you are using an API key from a sub-workspace. A sub-workspace cannot access applications or models in the root account workspace. To use a sub-workspace API key, the root account administrator must grant model authorization for the corresponding sub-workspace (for example, this topic uses the qwen3.8-max model). For detailed steps, see Configure model calling permissions.
How do I integrate withChatbox,Cherry Studio,Cline, orDify?
A: Follow the steps below based on your use case.
We use the most commonly used tools as examples. Steps for other tools are similar.
Chatbox
See Chatbox.
Cherry Studio
-
Click the Settings button in the lower-left corner. In the Model Service section, find Alibaba Cloud Model Studio. Enter your API key in API key. To obtain your API key, see Get an API Key. Enter
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/in API endpoint (replace {WorkspaceId} with your workspace ID). Click Add. -
In Model ID, enter the Qwen model you want to use. For more models, see the Qwen models in the Model list. Model Name and Group name are generated automatically.
-
Select the added model at the top of the interface. Some models support web search. Turn on the web search toggle next to the input box. Test it by entering “What’s the weather like in Hangzhou?”:
The web search button is the globe icon in the toolbar below the input box. After enabling it, the model successfully returned real-time weather information for Hangzhou and the weather forecast for the coming days, confirming that the web search feature is working correctly.
Cline
See Cline.
Dify
See Dify.
Next steps
| Explore more models | The example code uses |
| Learn advanced features | The example code covers basic Q&A only. To learn more about the Qwen API, such as streaming output, structured output, and function calling, see the Text generation model overview. |
| Try models in the browser | If you want to interact with models through a dialog box, like on the Qwen official website, go to the Playground.
|
| Call a custom-trained model | If you have deployed a custom-trained model on Model Studio, use the model code (not the model ID) from the model deployment page as the |
| Fine-tune models without code | Fine-tuning usually requires AI expertise. Model Studio provides no-code fine-tuning—you only need to provide a dataset. For details, see Fine-tune models in the console. |