All Products
Search
Document Center

Alibaba Cloud Model Studio:Make your first API call to Qwen

Last Updated:Jan 09, 2026

Alibaba Cloud Model Studio lets you call models through APIs. You can connect using OpenAI-compatible interfaces or the DashScope SDK.

This topic uses Qwen as an example to guide you through the process of calling a model API. You will learn how to:

  • Get an API key

  • Set up your local development environment

  • Call the Qwen API

Account settings

  1. Create an account: If you do not have an Alibaba Cloud account, create one first.

  2. Select a region and deployment mode: Model Studio is available in the Singapore, US (Virginia), and China (Beijing) regions. Your choice of region affects the model service's response speed, cost, available models, and default throttling. For more information, see Select region and deployment mode.

  3. Complete account verification: This step is required only if you want to activate the service in the China (Beijing) region. You can skip this step if you activate the service in the Singapore or US (Virginia) region.

    Use your Alibaba Cloud account to complete account verification:

    • Choose Individual Verification or Upgrade to Enterprise, and click Verify now.

    • In the Additional Information section of the page that appears, select Yes for Purchase cloud resources or enable acceleration inside the Chinese mainland.

    • For other items, see Account verification overview.

  4. Activate Model Studio: Use your Alibaba Cloud account to go to the Model Studio (Singapore, Virginia, or Beijing) console. After you read and agree to the Terms of Service, Model Studio is automatically activated. If the Terms of Service are not displayed, the service is already activated.

  5. Create an API key: Go to the Key Management (Singapore, Virginia, or Beijing) page and click Create API Key. You can then use the API key to call the model.

    When you create a new API key, we recommend that you set the Associated Workspace to Default workspace. To use an API key from a sub-workspace, a root account administrator must grant authorization for the model in that workspace (for example, this topic uses the Qwen-Plus model). For more information, see Authorize a sub-workspace to call models.

Set the API key as an environment variable

Set your API key as an environment variable to avoid exposing the key in your code and reduce the risk of leaks.

Procedure

Linux

Add permanent environment variable

If you want the API key environment variable to persist across all new sessions for the current user, add it as a permanent environment variable.

  1. Run the following command to add the environment variable to the ~/.bashrc file.

    # Replace YOUR_DASHSCOPE_API_KEY with your Alibaba Cloud Model Studio API key.
    echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.bashrc

    Alternatively, you can manually modify the ~/.bashrc file.

    Edit manually

    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 Alibaba Cloud Model Studio API key.
    export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"

    In the nano editor, press Ctrl + X, then press Y, and then press Enter to save and close the file.

  2. Run the following command to make the changes take effect.

    source ~/.bashrc
  3. Open another terminal window and run the following command to check whether the environment variable takes effect.

    echo $DASHSCOPE_API_KEY

Add temporary environment variable

If you want to use the environment variable only in the current session, add it as a temporary environment variable.

  1. Run the following command.

    # Replace YOUR_DASHSCOPE_API_KEY with your Alibaba Cloud Model Studio API key.
    export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
  2. Run the following command to check whether the environment variable takes effect.

    echo $DASHSCOPE_API_KEY

macOS

Add permanent environment variable

If you want the API key environment variable to persist across all new sessions for the current user, add it as a permanent environment variable.

  1. Run the following command in the terminal to view the default shell type.

    echo $SHELL
  2. Follow the steps that correspond to your default shell type.

    Zsh
    1. Run the following command to add the environment variable to the ~/.zshrc file.

      # Replace YOUR_DASHSCOPE_API_KEY with your Alibaba Cloud Model Studio API key.
      echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.zshrc

      Alternatively, you can manually modify the ~/.zshrc file.

      Edit manually

      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 Alibaba Cloud Model Studio API key.
      export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"

      In the nano editor, press Ctrl + X, then press Y, and then press Enter to save and close the file.

    2. Run the following command to make the changes take effect.

      source ~/.zshrc
    3. Open another terminal window and run the following command to check whether the environment variable takes effect.

      echo $DASHSCOPE_API_KEY
    Bash
    1. Run the following command to add the environment variable to the ~/.bash_profile file.

      # Replace YOUR_DASHSCOPE_API_KEY with your Alibaba Cloud Model Studio API key.
      echo "export DASHSCOPE_API_KEY='YOUR_DASHSCOPE_API_KEY'" >> ~/.bash_profile

      Alternatively, you can manually modify the ~/.bash_profile file.

      Edit manually

      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 Alibaba Cloud Model Studio API key.
      export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"

      To save and close the file in the nano editor, press Ctrl+X, then Y, and then Enter.

    2. Run the following command to make the changes take effect.

      source ~/.bash_profile
    3. Open another terminal window and run the following command to check whether the environment variable takes effect.

      echo $DASHSCOPE_API_KEY

Add temporary environment variable

If you want to use the environment variable only in the current session, add it as a temporary environment variable.

The following commands apply to Zsh and Bash.
  1. Run the following command.

    # Replace YOUR_DASHSCOPE_API_KEY with your Alibaba Cloud Model Studio API key.
    export DASHSCOPE_API_KEY="YOUR_DASHSCOPE_API_KEY"
  2. Run the following command to check whether the environment variable takes effect.

    echo $DASHSCOPE_API_KEY

Windows

In Windows, you can configure environment variables using System Properties, CMD, or PowerShell.

System properties

Note
  • An environment variable configured using this method is permanent.

  • You must have administrator permissions to modify system environment variables.

  • After you configure the environment variable, the change does not take effect immediately in open command windows, Integrated Development Environments (IDEs), or other running applications. You must restart these programs or open a new command line window for the environment variable to take effect.

  1. On the Windows desktop, press Win+Q, search for Edit the system environment variables in the search box, and open the System Properties window.

  2. In the System Properties window, click Environment Variables. Then, in the System variables area, click New. Set Variable name to DASHSCOPE_API_KEY and Variable value to your DashScope API key.

    image

  3. Click OK in all three open windows to save the changes and complete the environment variable configuration.

  4. Open a CMD window or a Windows PowerShell window and run the following command to check whether the environment variable takes effect.

    • CMD query command:

      echo %DASHSCOPE_API_KEY%

      image

    • Windows PowerShell query command:

      echo $env:DASHSCOPE_API_KEY

      image

CMD

Add permanent environment variable

If you want the API key environment variable to persist across all new sessions for the current user, you can perform the following steps.

  1. Run the following command in the Command Prompt.

    # Replace YOUR_DASHSCOPE_API_KEY with your Alibaba Cloud Model Studio API key.
    setx DASHSCOPE_API_KEY "YOUR_DASHSCOPE_API_KEY"
  2. Open a new Command Prompt window.

  3. Run the following command in the new Command Prompt window to check whether the environment variable takes effect.

    echo %DASHSCOPE_API_KEY%

    image

Add temporary environment variable

If you want to use the environment variable only in the current session, you can run the following command in the Command Prompt.

# Replace YOUR_DASHSCOPE_API_KEY with your Alibaba Cloud Model Studio API key.
set DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY

You can run the following command in the current session to check whether the environment variable takes effect.

echo %DASHSCOPE_API_KEY%

image

PowerShell

Add permanent environment variable

If you want the API key environment variable to persist across all new sessions for the current user, you can perform the following steps.

  1. Run the following command in PowerShell.

    # Replace YOUR_DASHSCOPE_API_KEY with your Alibaba Cloud Model Studio API key.
    [Environment]::SetEnvironmentVariable("DASHSCOPE_API_KEY", "YOUR_DASHSCOPE_API_KEY", [EnvironmentVariableTarget]::User)
  2. Open a new PowerShell window.

  3. Run the following command in the new PowerShell window to check whether the environment variable takes effect.

    echo $env:DASHSCOPE_API_KEY

    image

Add temporary environment variable

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 Alibaba Cloud Model Studio API key.
$env:DASHSCOPE_API_KEY = "YOUR_DASHSCOPE_API_KEY"

You can run the following command in the current session to check whether the environment variable takes effect.

echo $env:DASHSCOPE_API_KEY

image

Choose a programming language

Choose a familiar language or tool to call the model API.

Python

Step 1: Configure the Python environment

Check your Python version

You can enter the following commands in your terminal to check whether Python and pip are installed in your current computing environment:

Your Python version must be 3.8 or later, see Install Python.

python -V
pip --version

The following example uses CMD on Windows:

image

FAQ

Q: An error is reported when I run python -V or pip --version:

  • '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

Solution:

Windows
  1. Confirm that you have installed Python in your computing environment and added python.exe to the PATH environment variable. For more information, see Install Python.image

  2. If you have installed Python and added it to the environment variables but the error persists, close the current terminal, open a new one, and try again.

Linux and macOS

  1. Confirm that you have installed Python in your computing environment. For more information, see Install Python.

  2. If the error persists after you install Python, run the which python pip command to check whether python and pip exist in the system.

    • If the following result is returned, close the current terminal, open a new one, and try again.

      /usr/bin/python
      /usr/bin/pip
    • If the following result is returned, run which python3 pip3 to query 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 following result is returned, you can use python3 -V and pip3 --version to check the version.

      /usr/bin/python3
      /usr/bin/pip3

Configure a virtual environment (Optional)

If you have Python installed, you can create a virtual environment to install the OpenAI Python SDK or DashScope Python SDK. This helps you avoid dependency conflicts with other projects.

  1. Create a virtual environment

    You can run the following command to create a virtual environment named .venv:

    # If the command fails, you can replace python with python3 and run it again
    python -m venv .venv
  2. Activate the virtual environment

    If you are using Windows, run the following command to activate the virtual environment:

    .venv\Scripts\activate

    If you are using macOS or Linux, run the following command to activate the virtual environment:

    source .venv/bin/activate

Install the OpenAI Python SDK or DashScope Python SDK

You can use the OpenAI Python SDK or the DashScope Python SDK to call models on the Model Studio platform.

Install the OpenAI Python SDK

Run the following command to install or upgrade the OpenAI Python SDK:

# If the command fails, you can replace pip with pip3 and run it again
pip install -U openai

image

When the terminal displays the message Successfully installed ... openai-x.x.x, the OpenAI Python SDK is installed.

Install the DashScope Python SDK

Run the following command to install or upgrade the DashScope Python SDK:

# If the command fails, you can replace pip with pip3 and run it again
pip install -U dashscope

image

When the terminal displays the message Successfully installed ... dashscope-x.x.x, the DashScope Python SDK is installed.

Step 2: Call the model API

OpenAI Python SDK

If you have installed Python and the OpenAI Python SDK, follow these steps to send your API request.

  1. Create a new file named hello_qwen.py.

  2. Copy the following code to hello_qwen.py and save the file.

    import os
    from openai import OpenAI
    
    try:
        client = OpenAI(
            # API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
            # If the environment variable is not configured, replace the following line with: api_key="sk-xxx", using your Model Studio API key.
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            # Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
            # - Singapore: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
            # - US (Virginia): https://dashscope-us.aliyuncs.com/compatible-mode/v1
            # - China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1
            base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
        )
    
        completion = client.chat.completions.create(
            model="qwen-plus",  
            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("For more information, see the documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code")
  3. Run python hello_qwen.py or python3 hello_qwen.py from the command line.

    If the message No such file or directory is displayed, you must specify the full file path.

    After running the command, you will see the following output:

    I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.

DashScope Python SDK

If you have installed Python and the DashScope Python SDK, follow these steps to send your API request.

  1. Create a new file named hello_qwen.py.

  2. Copy the following code to hello_qwen.py and save the file.

    import os
    from dashscope import Generation
    import dashscope
    # Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
    # - Singapore: https://dashscope-intl.aliyuncs.com/api/v1
    # - US (Virginia): https://dashscope-us.aliyuncs.com/api/v1
    # - China (Beijing): https://dashscope.aliyuncs.com/api/v1
    dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
    
    messages = [
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': 'Who are you?'}
        ]
    response = Generation.call(
        # API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
        # If the environment variable is not configured, replace the following line with: api_key = "sk-xxx", using your Model Studio API key.
        api_key=os.getenv("DASHSCOPE_API_KEY"), 
        model="qwen-plus",   
        messages=messages,
        result_format="message"
    )
    
    if response.status_code == 200:
        print(response.output.choices[0].message.content)
    else:
        print(f"HTTP status code: {response.status_code}")
        print(f"Error code: {response.code}")
        print(f"Error message: {response.message}")
        print("For more information, see the documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code")
  3. Run python hello_qwen.py or python3 hello_qwen.py from the command line.

    Note

    The command in this example must be run in the directory where the Python file is located. To run it from any location, specify the full file path.

    After running the command, you will see the following output:

    I am a large-scale language model from Alibaba Cloud. My name is Qwen.

Node.js

Step 1: Configure the Node.js environment

Check the Node.js installation status

You can enter the following commands in your terminal to check whether Node.js and npm are installed in your current computing environment:

node -v
npm -v

The following example uses CMD on Windows:

image

This command prints your current Node.js version. If Node.js is not in your environment, go to the Node.js official website to download it.

Install the model calling SDK

You can run the following command in the terminal:

npm install --save openai
# Or
yarn add openai
Note

If the installation fails, you can configure a traffic mirror source to complete the installation. For example:

npm config set registry https://registry.npmmirror.com/

After you configure the traffic mirror source, you can run the SDK installation command again.

image

When the terminal displays the message added xx package in xxs, the OpenAI SDK is installed. You can use npm list openai to query the specific version information.

Step 2: Call the model API

  1. Create a new hello_qwen.mjs file.

  2. Copy the following code into the file.

    import OpenAI from "openai";
    
    try {
        const openai = new OpenAI(
            {
                // API keys for the Singapore, US (Virginia), and China (Beijing) regions are different. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
                // If the environment variable is not configured, replace the following line with: apiKey: "sk-xxx", using your Model Studio API key.
                apiKey: process.env.DASHSCOPE_API_KEY,
                // Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
                // - Singapore: https://dashscope-intl.aliyuncs.com/compatible-mode/v1
                // - US (Virginia): https://dashscope-us.aliyuncs.com/compatible-mode/v1
                // - China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1
                baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
            }
        );
        const completion = await openai.chat.completions.create({
            model: "qwen-plus",  
            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("For more information, see the documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
    }
  3. Run the following command from the command line to send the API request:

    node hello_qwen.mjs
    Note
    • The command in this example must be run in the directory where the hello_qwen.mjs file is located. To run it from any location, specify the full file path.

    • Make sure that the SDK is installed in the same directory as the hello_qwen.mjs file. If the SDK and the file are in different directories, the error Cannot find package 'openai' imported from xxx is reported.

    After the command runs successfully, you will see the following output:

    I am a language model from Alibaba Cloud. My name is Qwen.

Java

Step 1: Configure the Java environment

Check your Java version

You can run the following command in the terminal:

java -version
# (Optional) If you use Maven to manage and build Java projects, you must also make sure that Maven is correctly installed in your development environment
mvn --version

The following example uses CMD on Windows:

image

To use the DashScope Java SDK, you need Java 8 or later. You can check the first line of the output to confirm the Java version. For example, the message openjdk version "16.0.1" 2021-04-20 indicates that the current Java version is Java 16. If Java is not installed in your current computing environment, or if the version is earlier than Java 8, go to Java Downloads to download and install it.

Install the model calling SDK

If Java is installed in your environment, install the DashScope Java SDK. For SDK versions, see DashScope Java SDK. Run the following command to add the Java SDK dependency. Replace the-latest-version with the latest version number.

XML

  1. Open the pom.xml file of your Maven project.

  2. Add the following dependency information within 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>
  3. Save the pom.xml file.

  4. Use a Maven command, such as mvn compile or mvn clean install, to update the project dependencies. Maven will automatically download and add the DashScope Java SDK to your project.

The following example uses the IntelliJ IDEA integrated development environment (IDE) on Windows:

image

Gradle

  1. Open the build.gradle file of your Gradle project.

  2. Add the following dependency information within the dependencies block.

    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'
    }
  3. Save the build.gradle file.

  4. In the command line, switch to your project's root directory and run the following Gradle command to update the project dependencies. This will automatically download and add the DashScope Java SDK to your project.

    ./gradlew build --refresh-dependencies

The following example uses the IntelliJ IDEA IDE on Windows:

image

Step 2: Call the model API

You can run the following code to call the model API.

import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
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 GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
        // - Singapore: https://dashscope-intl.aliyuncs.com/api/v1
        // - US (Virginia): https://dashscope-us.aliyuncs.com/api/v1
        // - China (Beijing): https://dashscope.aliyuncs.com/api/v1
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("Who are you?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
                // If the environment variable is not configured, replace the following line with: .apiKey("sk-xxx"), using your Model Studio API key.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Model list: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
    public static void main(String[] args) {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("Error message: "+e.getMessage());
            System.out.println("For more information, see the documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

After running the code, you will see the corresponding output:

I am a large-scale language model developed by Alibaba Cloud. My name is Qwen.

curl

You can call models on the Model Studio platform using the OpenAI-compatible HTTP method or the DashScope HTTP method. For a list of models, see Models.

Note

If the environment variable is not configured, replace -H "Authorization: Bearer $DASHSCOPE_API_KEY" \ with -H "Authorization: Bearer sk-xxx" \ and use your Model Studio API key.

OpenAI compatible HTTP

The URL in the code example is for the "International (Singapore)" region. If you use a model in the "Chinese mainland (Beijing)" region, you must replace the URL with https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions.

You can run the following command to send an API request:

Windows

Run the following command in Command Prompt (CMD):

# ======= Important =======
# API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
# - Singapore: https://dashscope-int.aliyuncs.com/compatible-mode/v1/chat/completions
# - US (Virginia): https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# - China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before running ===

curl -X POST "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions" \
-H "Authorization: Bearer %DASHSCOPE_API_KEY%" \
-H "Content-Type: application/json" \
-d "{
    \"model\": \"qwen-plus\",
    \"messages\": [
        {
            \"role\": \"system\",
            \"content\": \"You are a helpful assistant.\"
        },
        {
            \"role\": \"user\",
            \"content\": \"Who are you?\"
        }
    ]
}"

Linux/macOS

Run the following command in the Terminal:

# ======= Important =======
# API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
# - Singapore: https://dashscope-int.aliyuncs.com/compatible-mode/v1/chat/completions
# - US (Virginia): https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# - China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before running ===

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "Who are you?"
        }
    ]
}'

After sending the API request, you will receive the following 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": "qwen-plus",
    "id": "chatcmpl-39799876-eda8-9527-9e14-2214d641cf9a"
}

DashScope HTTP

The URL in the code example is for the Singapore region.

  • If you use a model in the US (Virginia) region, you must replace the URL with https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation.

  • If you use a model in the China (Beijing) region, you must replace the URL with https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation.

You can run the following command to send an API request:

Windows

Run the following command in Command Prompt (CMD):

# ======= Important =======
# API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
# - Singapore: https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# - US (Virginia): https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# - China (Beijing): https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === Delete this comment before running ===

curl -X POST "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer %DASHSCOPE_API_KEY%" \
-H "Content-Type: application/json" \
-d "{
  \"model\": \"qwen-plus\",
  \"input\": {
    \"messages\": [
      {
        \"role\": \"system\",
        \"content\": \"You are a helpful assistant.\"
      },
      {
        \"role\": \"user\",
        \"content\": \"Who are you?\"
      }
    ]
  },
  \"parameters\": {
    \"result_format\": \"message\"
  }
}"

Linux/macOS

Run the following command in the Terminal:

# ======= Important =======
# API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
# - Singapore: https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# - US (Virginia): https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# - China (Beijing): https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === Delete this comment before running ===

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format":"message"
    }
}'

After sending the API request, you will receive the following response:

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "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 API

package 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://www.alibabacloud.com/help/zh/model-studio/getting-started/models
		Model: "qwen-plus",
		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)
	}
	// Create a POST request. Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
        // - Singapore: https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
        // - US (Virginia): https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
        // - China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
	req, err := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}
	// Set the request header
	// API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
	// If the environment variable is not configured, replace the following line with: apiKey := "sk-xxx", using your Model Studio API key.
	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 content
	fmt.Printf("%s\n", bodyText)
}
<?php
// Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
// - Singapore: https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
// - US (Virginia): https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
// - China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
// If the environment variable is not configured, replace the following line with: $apiKey = "sk-xxx"; using your Model Studio API key.
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set the request header
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// Set the request body
$data = [
    "model" => "qwen-plus",
    "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)
    {
        // API keys for the Singapore, US (Virginia), and China (Beijing) regions are not interchangeable. Get API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
        // If the environment variable is not configured, replace the following line with: string? apiKey = "sk-xxx"; using your Model Studio 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;
        }
        // Note: The base_url is different for each region. The example below uses the base_url for the Singapore region.
        // - Singapore: https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
        // - US (Virginia): https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
        // - China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
        string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
        // Model list: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen-plus"",
            ""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 the request header
            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);

            // Process the response
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"Request failed: {response.StatusCode}";
            }
        }
    }
}

API reference

  • For the input and output parameters of the Qwen API, see Qwen.

  • For other models, see Models.

FAQ

What to do if the error Model.AccessDenied is reported after I call a 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 default workspace. To use a model such as Qwen-Plus, a root account administrator must grant authorization to the sub-workspace, see Set model calling permissions.

Next steps

View more models

The example code uses the qwen-plus model. Model Studio also supports other Qwen models. For a list of supported models and their corresponding API references, see Models.

Learn about advanced usage

The sample code covers only basic Q&A. To learn about advanced features of the Qwen API, such as streaming output, structured output, and function calling, see the Overview of text generation models folder.

Try the model online

If you want to interact with the model through a dialog box, similar to the experience on Qwen Chat, you can visit the Playground (Singapore, Virginia, or Beijing).