Call an API

Updated at:
Copy as MD

After an API is published to API Gateway, callers must use the credentials of an authorized app to access it. This topic describes the entire process of preparing to call an API, from creating an app, granting authorization, and choosing an authentication method to obtaining credentials and making calls using an SDK.

Prerequisites

Before you call any DataService Studio API, you must meet the following three prerequisites:

Prerequisite

Description

Responsible role

API is published

The API must be approved and published to API Gateway to generate an online calling endpoint. For more information, see Publish an API.

API developer

An app is created

The caller must have an app in API Gateway to act as its identity when calling an API.

API caller

Authorization is granted

The app must be authorized to call the target API; otherwise, API Gateway denies access, even with valid credentials. For more information, see API Gateway authorization.

API developer/administrator

You can think of the relationship between these three elements as follows: the API is the "door," the app is the "ID card," and authorization is the "pass." You can only pass through the door if you present both a valid ID card and the corresponding pass.

Create an app (app identity)

An app acts as a container for the credentials you use to call an API. Each app has an independent set of authentication information (AppKey, AppSecret, and AppCode), which is equivalent to an account and password for the app.

Automatically created default app

When you publish an API in DataWorks for the first time, the system automatically creates an app with the same name as the workspace in API Gateway. All APIs in that workspace are then automatically authorized for this default app. This means that:

  • Members within the same workspace can directly use the default app's credentials to call APIs in that workspace.

  • You can view the authentication credentials for the default app on the Call APIs page in the DataService Studio console.

Create an app manually

If you need to isolate traffic or differentiate permissions for different callers, you can create new apps manually in the API Gateway console:

  1. Log in to the API Gateway console.

  2. In the left-side navigation pane, select Application Management.

  3. Click Create App, and enter a name and description for the app.

  4. After the app is created, the system generates an AppKey, AppSecret, and AppCode for it.

Note

Create separate apps for different calling scenarios, such as internal systems, third-party partners, or data dashboards. This practice simplifies subsequent traffic monitoring, throttling, and permission management.

Authorization process

Authorization is the process of granting an app permission to call a specific API. Only an authorized app can use its credentials to successfully call the API.

Authorize other accounts

When you need to make an API available to workspaces under other Alibaba Cloud accounts, you must perform cross-account authorization:

  1. Log on to the DataWorks console. In the target region, click Data Analysis and Service > DataService Studio in the left-side navigation pane. Select a workspace from the drop-down list and click Go to DataService Studio.

  2. On the Data Services page, click Service Management in the top menu bar to open the Manage APIs page.

  3. On the Published APIs tab, find the target API and click Authorization in the Actions column.

  4. In the API authorization dialog box, configure the following parameters:

    API授权

    Parameter

    Description

    API Name

    The name of the API to be authorized. This parameter cannot be modified.

    Alibaba Cloud account ID to authorize

    The ID of the Alibaba Cloud account that requires permission to call this API. You can find your account ID on the page.

    Authorized Workspace

    Select the name of the workspace under the target Alibaba Cloud account.

    Authorization Validity Period

    Select the validity period for the authorization (described in the following section).

  5. Click Confirm to complete the authorization.

Authorization validity period

The authorization validity period determines the time range during which the authorized party can call the API:

Validity type

Description

Use cases

Limited

The authorization is valid until the selected expiration date.

Temporary data sharing, limited-time collaborative projects, and trial scenarios.

Unlimited

The authorization is permanent unless it is manually revoked.

Long-term stable system integrations and internal service-to-service calls.

Note

If an authorized API is taken offline or deleted, callers can no longer access it. If an API is taken offline and then republished (or modified and republished), the API owner must reauthorize the new version.

View authorization status

On the Manage APIs page, you can view the authorization status from two perspectives:

View APIs you are authorized to call

Click the Authorized to Use tab to view a list of all APIs that other accounts have authorized you to call. On this page, you can:

  • Click Test to test an authorized API online. For more information, see Test an API.

  • Click Delete to voluntarily relinquish the authorization to call an API.

View APIs you have authorized for others

Click the Authorize Others to Use tab to view a list of APIs that you have authorized for other workspaces. On this page, you can:

  • Click Test to test an authorized API online.

  • Click Manage to cancel or modify the authorization for a specific workspace.

Three authorization scenarios

The granularity of API authorization varies based on team size and security management requirements. The following three scenarios cover the most common authorization strategies.

Scenario 1: One workspace, one shared app

场景一

Scenario description: All members of a single DataWorks workspace use the same default app to call APIs.

When to use: Small teams with a high level of trust among members; no need to differentiate traffic sources from different members; quick start with minimal configuration.

How it works: When an API is published, DataWorks automatically creates an app with the same name as the workspace and grants it authorization for all APIs within that workspace. All members of the workspace share this set of AppKey, AppSecret, and AppCode.

Pros: Zero-configuration and ready to use out of the box. Cons: You cannot trace calls to individual members, and a credential leak affects the entire workspace.

Scenario 2: One app per RAM user

场景二

Scenario description: Each RAM user (sub-account) in an enterprise creates a separate app in API Gateway and receives individual authorization to call APIs.

When to use: You need to accurately track the API call activity of each user, apply different throttling policies to different users, or meet high security and compliance requirements that mandate "one credential per person".

How it works: Each RAM user logs in to the API Gateway console to create their own app. The API administrator grants authorization to each user's app. Each user then calls APIs using the credentials of their own app.

Pros: Call activity is traceable to individual users, providing strong security isolation. The impact of a credential leak is minimal. Cons: Higher management overhead, as each new user requires app creation and authorization configuration.

Scenario 3: One app per user group

场景三

Scenario description: Multiple RAM users are divided into groups based on business function or team, and members of each group share a single app to call APIs.

When to use: Larger teams organized by department or project; a need to differentiate traffic from different business lines but not from individuals; a balance between management cost and security.

How it works: An app is created for each business group. The API administrator grants API authorization to each group's app. Members within a group share the credentials of their group's app.

Pros: Offers a moderate level of management granularity, allowing for business-level differentiation without excessive administrative overhead. Cons: No further differentiation is possible among members within the same group.

Scenario comparison

Dimension

Scenario 1 (Shared app)

Scenario 2 (Separate apps)

Scenario 3 (Grouped apps)

Management complexity

Low

High

Medium

Security isolation

Low

High

Medium

Traffic tracking granularity

Workspace-level

User-level

Business group-level

Impact of credential leak

Entire workspace

Individual only

Business group only

Recommended team size

Fewer than 5 members

Any size

More than 10 members

Distinguishing credential types

DataService Studio involves three distinct types of authentication credentials. It is crucial to understand their different purposes, sources, and use cases to avoid confusion:

Credential type

Purpose

Source

Use case

API calling credentials (AppKey/AppSecret/AppCode)

To authenticate the caller when calling a published API.

API Gateway > App Management

Calling a DataService Studio API from client-side code.

Data source connection credentials (AccessKey ID/AccessKey Secret)

To authenticate DataService Studio's connection to a backend data source.

Alibaba Cloud RAM > AccessKey Management

Entered on the data source configuration page to allow DataService Studio to connect to your database.

DataWorks platform permissions (RAM user/role)

To control who can perform operations on APIs in the DataWorks console.

Alibaba Cloud RAM > Users/Roles

Logging in to DataWorks and creating, publishing, or managing APIs.

In a nutshell: AccessKey is for connecting to data sources, AppKey is for calling APIs, and RAM is for accessing the console. Each serves a distinct purpose, and they are not interchangeable.

Common confusion 1: "I'm getting a 403 error when calling an API, but I have RAM administrator permissions." — RAM permissions control access to the DataWorks console, not the ability to call an API. API call permissions are controlled by app authorizations. Even if you are a RAM administrator, you still need the AppKey and AppSecret of an authorized app to call an API.

Common confusion 2: "Is the AccessKey for the data source configuration the same as the AppKey for API calls?" — No. The AccessKey is used by the DataService Studio backend to connect to a data source, whereas the AppKey is used by a caller to invoke an API. The two are completely independent.

Common confusion 3: What should I enter for "account ID" on the authorization page? — The authorization page requires the Alibaba Cloud account ID (a numeric string), not a RAM username or logon email. To find your account ID, log in to the Account Management page and check the security settings.

Authentication methods

API Gateway supports two authentication methods. By default, DataService Studio adds "Alibaba Cloud App Authentication" to APIs within a workspace. Callers can choose a specific authentication method based on their security requirements.

Simple authentication (AppCode)

The caller only needs to add the AppCode to the HTTP request header to complete authentication. No signature calculation is required.

Request example:

GET /api/v1/users?name=test HTTP/1.1
Host: your-api-endpoint.cn-shanghai.alicloudapi.com
Authorization: APPCODE 3f963a8e1cd7492bbd8a5e2e5e4c****

Signature authentication (AppKey + AppSecret)

The caller must use the AppSecret to calculate an HMAC-SHA256 signature for the request content and add the AppKey and the signature value to the request headers. When API Gateway receives the request, it recalculates the signature using the same AppSecret and compares it with the received signature to verify the caller's identity.

Request example (headers only):

X-Ca-Key: 12345678
X-Ca-Signature: BASE64_ENCODED_SIGNATURE
X-Ca-Timestamp: 1741593600000
X-Ca-Nonce: unique-uuid-string
X-Ca-Signature-Headers: X-Ca-Key,X-Ca-Nonce,X-Ca-Timestamp

Method comparison

Item

Simple authentication (AppCode)

Signature authentication (AppKey + AppSecret)

Security level

Low

High

Implementation complexity

Very low (single header line)

Medium (requires implementing a signature algorithm)

Replay attack prevention

Not supported

Supported (based on timestamp and nonce)

Tamper resistance

Not supported

Supported (request content is included in the signature)

Use cases

Internal system debugging, data dashboards, rapid prototype validation.

Production environments, publicly exposed APIs, and scenarios with high security and compliance requirements.

Transport requirements

Use with HTTPS is strongly recommended.

Provides some security even over HTTP, but HTTPS is still recommended.

Note

Recommendations

  • Development and testing: Use the AppCode method to quickly validate API functionality and reduce development costs.

  • Production environment: Always use AppKey + AppSecret signature authentication, combined with HTTPS for transport encryption.

  • Publicly exposed APIs: You must use signature authentication to prevent replay attacks if credentials are intercepted during transmission.

Signature algorithm

Signature authentication is based on the HMAC-SHA256 algorithm. The core process is as follows:

Signature process

  1. Construct the string to sign: Concatenate the HTTP method (for example, GET or POST), Accept header, Content-MD5 (MD5 value of the request body), Content-Type, Date, custom headers to be signed (X-Ca-*, sorted alphabetically), and the canonicalized URL (path + sorted query parameters).

  2. Calculate the signature using HMAC-SHA256: Signature = Base64(HMAC-SHA256(AppSecret, StringToSign))

  3. Add the signature information to the request headers: This includes X-Ca-Key (the AppKey), X-Ca-Signature (the signature), X-Ca-Timestamp (a millisecond-level timestamp), X-Ca-Nonce (a UUID to prevent replay attacks), and X-Ca-Signature-Headers (a list of the headers included in the signature).

Key considerations

Pay attention to the following details when implementing the signature algorithm to avoid common errors:

  • Parameter sorting: URL query parameters and headers included in the signature must be sorted alphabetically by key (in ASCII order).

  • URL encoding: Special characters in parameter values, such as spaces or non-ASCII characters, must be URL-encoded.

  • Newline characters: Use a line feed character (\n, LF) to separate lines in the string to sign. Do not use a carriage return and line feed combination (\r\n, CRLF).

  • Empty value handling: If the request has no body, the Content-MD5 value is an empty string (not null). If headers such as Accept do not exist, use an empty string for them as well.

  • Timestamp precision: The X-Ca-Timestamp must be a millisecond-level timestamp. The time difference between the client and the server cannot exceed 15 minutes.

  • Nonce uniqueness: A unique UUID must be generated as the X-Ca-Nonce for each request. Reusing a nonce triggers the replay attack prevention mechanism.

Note

For complete code examples in Java and Python, detailed rules for constructing the string to sign, and methods for debugging common signature errors, see the Signature algorithm topic in the API Gateway documentation.

View authentication credentials

After you create an app and grant it authorization, you need to obtain the AppKey, AppSecret, or AppCode to make API calls. DataService Studio provides a convenient way to view these credentials.

View credentials in the DataService Studio console

  1. Log on to the DataWorks console. In the target region, click Data Analysis and Service > DataService Studio in the left-side navigation pane. Select a workspace from the drop-down list and click Go to DataService Studio.

  2. On the DataService Studio page, click Service Management in the top menu bar.

  3. In the left-side navigation pane, click Call APIs.

  4. On the Call APIs page, you can view and copy the following authentication credentials: AppKey (the unique identifier of the app), AppSecret (used for signature authentication; keep it confidential), and AppCode (used for simple authentication).

View credentials in the API Gateway console: Log in to the API Gateway console, find the target app in App Management, and go to its details page to view the AppKey, AppSecret, and AppCode.

Important

AppSecret and AppCode are sensitive information. Do not expose them in code repositories, logs, front-end pages, or other public locations. If you suspect that your credentials have been compromised, reset the AppSecret immediately in the API Gateway console.

Call an API with the API Gateway SDK

API Gateway provides SDKs for various programming languages to help you quickly integrate API calls. The SDKs have a built-in implementation of the signature algorithm, so you do not need to calculate the signature manually. You only need to provide your AppKey and AppSecret. For more information, see the Call an API documentation and SDK Download and Usage.

Supported SDK languages

Language

Description

Java

Supports import through Maven dependency and provides synchronous and asynchronous calling methods.

Python

Supports installation via pip and is compatible with Python 2.7 and 3.x.

Node.js

Supports installation via npm.

PHP

Supports installation via Composer.

C#

Supports NuGet package management.

Go

Supports installation via go get.

Advantages of using an SDK

Compared with manually constructing HTTP requests, using an SDK to make API calls offers the following advantages:

  • Automatic signing: The SDK implements the HMAC-SHA256 signature algorithm, so developers do not need to handle signing details.

  • Automatic retries: Some SDKs have a built-in retry mechanism for network exceptions.

  • Parameter validation: The SDK validates basic parameters before sending a request.

  • Performance optimization: SDKs typically use connection pooling and technologies such as HTTP/2 to optimize network performance.

Quick integration example (Java)

The following example shows how to use the API Gateway Java SDK to call a DataService Studio API:

// 1. Add the Maven dependency
// <dependency>
//     <groupId>com.aliyun.api.gateway</groupId>
//     <artifactId>sdk-core-java</artifactId>
//     <version>LATEST_VERSION</version>
// </dependency>

// 2. Initialize the client
HttpClientBuilderParams params = new HttpClientBuilderParams();
params.setAppKey("your_app_key");
params.setAppSecret("your_app_secret");

ApacheHttpClient client = new ApacheHttpClient(params);

// 3. Construct the request
IoTApiRequest request = new IoTApiRequest();
request.setDomain("your-api-endpoint.cn-shanghai.alicloudapi.com");
request.setPath("/api/v1/query");
request.setHttpMethod("GET");
request.putQueryParam("pageSize", "10");
request.putQueryParam("pageNum", "1");

// 4. Make the call
ApiResponse response = client.execute(request);
System.out.println("Response: " + response.getBody());

Quick integration example (Python)

# 1. Install the SDK
# pip install aliyun-api-gateway-sdk

# 2. Call the API
from com.alibaba.cloudapi.sdk.client import DefaultClient
from com.alibaba.cloudapi.sdk.model import HttpClientBuilderParams

params = HttpClientBuilderParams()
params.app_key = "your_app_key"
params.app_secret = "your_app_secret"
params.host = "your-api-endpoint.cn-shanghai.alicloudapi.com"

client = DefaultClient(params)
response = client.get(
    path="/api/v1/query",
    query_params={"pageSize": "10", "pageNum": "1"},
    headers={"Accept": "application/json"}
)

print(f"Status: {response.status_code}")
print(f"Body: {response.content}")
Note

For detailed instructions, API references, and code samples for each language SDK, see the SDK Download and Usage topic in the official API Gateway documentation.

End-to-end workflow

The end-to-end workflow begins when a developer publishes an API, which automatically creates and authorizes a default app. To share the API across accounts, the owner must manually grant authorization. The API caller then obtains credentials (AppKey, AppSecret, or AppCode) from an app and chooses an authentication method. Finally, the caller uses an SDK or a direct HTTP request to call the API. API Gateway validates the request, DataService Studio executes the query, and the result is returned to the caller.