Create a query API (Direct data source mode)

Updated at:

Learn how to create an API to query data with SQL directly from a data source using the direct connection mode.

Limits

  • In an API call, if the data source supports pagination and the API operation is List, you can use the PageStart and PageSize parameters to configure pagination, regardless of whether paginated query is enabled.

  • In advanced SQL mode, if an API's SQL script uses a LIMIT clause, the OrderByList parameter sorts only the rows returned by that clause. This means LIMIT takes precedence over OrderByList. For example: sort by phone_no, take the first 10 rows, and then sort those rows by paper_no.

    SELECT * FROM (
      select paper_no,phone_no,vip_no from aaaa order by phone_no limit 1,10
      ) T0 -- This is the SQL script in the API
    ORDER BY paper_no ASC -- This is the statement executed when OrderByList is specified in the API call
  • When creating an API with basic SQL, paginated query is not supported if the SQL script includes a LIMIT clause.

  • For a list of data sources that support direct SQL connection, row-level security, and paginated queries, see Data sources supported by Data Service.

Permissions

In projects that support this service, project administrators and developers can generate APIs.

Asynchronous call workflow

This diagram shows the complete lifecycle of an asynchronous data query, from obtaining a job ID and checking its status to retrieving the result and closing the job.

image
  • Asynchronous call query workflow:

    • GetJobStatus: Gets the job's execution status.

    • GetJobResult: Returns the job result. You can call this operation only when the job status is Success. Otherwise, the call fails. This operation only retrieves query results sequentially.

    • GetJobExecutionLog: Gets the job's execution log.

    • CloseJob: Completes the request and releases all resources used by the job, such as database connections and cache. Call this operation to release resources, even if the job status is Failed.

  • Asynchronous call cancellation workflow:

    CancelJob: Cancels a query job. If a database query is in progress, the query is canceled synchronously. You cannot cancel a job that has not started or has already completed.

Step 1: Create an API

  1. In the top navigation bar of the Dataphin homepage, select service > API development.

  2. In the upper-left corner, select a project. In the left-side navigation pane, click API service, and then on the API page, click + New API.

  3. In the New API dialog box, select direct connection to data source-SQL mode.

Step 2: Configure API parameters

  1. On the Create API page, configure the API's basic information and parameter settings.

    API basic information

    Parameter

    Description

    API name

    Enter a name for the API. The name must follow these rules:

    • Can contain Chinese characters, letters, digits, and underscores (_).

    • Must be 4 to 100 characters long.

    • Must start with a Chinese character or a letter.

    • Must be globally unique.

    Operation type

    • GET: Requests a specific resource from the server.

    • LIST: Requests a set of resources from the server.

    Data update frequency

    Specifies how often the API's returned data is updated. This information helps callers understand data freshness. Supported frequencies are Daily, Hourly, Minutely, and Custom. If you select Custom, you can enter a value up to 128 characters long.

    API group

    Select the API group for the API. To create an API group, see Create Service Group.

    Description

    Enter a description for the API (up to 128 characters).

    Protocol

    The protocol for the data generation API. HTTP and HTTPS are supported.

    • HTTP: Hypertext Transfer Protocol, the most widely used network protocol.

    • HTTPS: If the gateway is configured as an Alibaba Cloud API Gateway (dedicated or shared instance), you can select HTTPS. Ensure the SSL certificate for your custom domain name is valid to prevent invocation failures. To configure the SSL certificate, go to Platform Management Network Configuration and make the changes on the Network Configuration page.

    Invocation mode

    Specifies the communication pattern between the client and server. You can select synchronous invocation or asynchronous invocation. The default is synchronous invocation.

    • Synchronous invocation: A client sends a request and must wait for the server's response before sending another request. For complex queries, the response time can be long, and waiting occupies server connections, increasing server load. This mode is suitable for scenarios that require high real-time performance and short processing times.

    • Asynchronous invocation: A client sends a request and can continue sending other requests without waiting for a response. The server notifies the client after the request is processed. This mode is suitable for long-running, non-real-time tasks, such as batch processing. When fetching data in batches, it can reduce the duplication of database query results.

    Execution timeout

    Available only for asynchronous invocation. This setting specifies the maximum SQL execution duration. The default is 60 seconds, and the supported range is any positive integer from 1 to 7,200 (2 hours).

    Timeout

    Specifies the maximum duration for an API call. For synchronous invocation, the default is 3 seconds, and you can set it to any positive integer from 3 to 60. For asynchronous invocation, the default is 600 seconds, and you can set it to any positive integer from 3 to 7,200 (2 hours).

    If an API call exceeds the specified timeout, an error is reported, allowing you to promptly identify and handle exceptions. For more information on viewing exceptions, see View and Manage Operation and Maintenance Monitoring APIs.

    Maximum returned records

    Available when the Operation Type is LIST. An API can return a maximum of 10,000 records. You can enter any positive integer from 1 to 10,000.

    Cache settings

    This setting is available only for synchronous invocation. You can Enable or Disable it. If enabled, you must configure the Cache Duration. The default is 300 seconds. You can set it to any positive integer from 60 to 1,000,000 seconds (approximately 277.78 hours).

    Version number

    Enter a version number. Each API configuration must have a unique version number, which allows you to compare different versions. The version number must follow these rules:

    • Cannot exceed 64 characters.

    • Can contain uppercase and lowercase letters, digits, underscores (_), periods (.), and hyphens (-).

    Return type

    The default is JSON.

    Return SQL

    Controls whether the API response includes the SQL statement that was executed.

    • The API response returns the physical SQL statement executed against the database.

    • The API response shows the original SQL script.

    API request and response parameter configuration

    Configuring an API's request parameters and response parameters involves identifying the source tables, writing the SQL script, parsing the parameters, and then configuring their details.

    1. In the API Parameter Configuration section, identify the source tables for the input and output parameters, and write the API SQL script based on the Reference Example.

      image

      Parameter

      Description

      Mode

      Select the environment for the data source. You can select Basic or Dev-Prod.

      • In Basic mode, all operations (development, submission, and publishing) read from the production database.

      • In Dev-Prod mode, development and submission operations read from the development database, while published APIs read from the production database.

      Data source

      Select a data source based on its type. For a list of data sources that support asynchronous invocation, see Data Sources Supported by Data Service.

      Note

      MySQL versions 5.1.43, 5.6, 5.7, and 8 are supported.

      Query acceleration

      This parameter is available for MaxCompute data sources. When enabled, this feature uses MaxCompute Query Acceleration (MCQA) to accelerate queries, reducing execution times to seconds. Each tenant has limits on the number of MCQA jobs and concurrency. Exceeding these limits may cause acceleration to fail. For information on how to resolve execution errors, see Query Acceleration (MCQA).

      SQL mode

      Select either basic SQL or advanced SQL mode.

      • Basic SQL: Write query logic using basic SQL syntax. For examples, see Reference Example.

      • Advanced SQL: Write query logic using SQL with MyBatis tags. Supported tags include if, choose, when, otherwise, trim, foreach, and where. For examples, see Reference Example.

      Result pagination

      This setting is available for synchronous invocations when the Operation Type is List. When enabled, you must specify a sort field to ensure stable pagination and prevent duplicate or missing results. If disabled, the pagination parameters (PageStart and PageSize) are not displayed on the API debugging or testing page. You can clear the Hide Parameters checkbox to display them.

      Sort priority

      • When SQL mode is set to Basic SQL, you can select the sort priority.

        • SQL Script: If a sort order is specified in the SQL script, the OrderByList in the common request parameters has no effect.

        • OrderByList Request Parameter: During testing or debugging, both the sorting defined in the SQL script and the OrderByList common request parameter are applied. The OrderByList parameter has a higher priority.

      • When SQL mode is set to Advanced SQL, during testing or debugging, both the sorting defined in the SQL script and the OrderByList common request parameter are applied. The OrderByList parameter has a higher priority.

      Note

      Sort priority cannot be configured for the following data sources: HBase 0.9.4/1.1.x/2.x, TDengine, and SAP HANA.

      API SQL script editor

      For guidelines on how to write your API SQL script, see API SQL Script Editing Instructions.

      Reference example

      The following are SQL script templates from which Dataphin can parse request and response parameters:

      • Get/List Basic SQL Examples:

        -- Example 1: Query a single record based on a condition. If 'id' is not required and not passed as a parameter, the condition is automatically ignored.
        SELECT id,name FROM tablename WHERE id = ${id}
        
        -- Example 2: Batch query using an IN condition. The 'id_list' parameter is a comma-separated list.
        SELECT id,name FROM tablename WHERE id in (${id_list})
        
        -- Example 3: Use LIKE for fuzzy matching and use semantic aliases for aggregate functions.
        SELECT MAX(a) AS max_a, SUM(a) AS sum_a, MIN(a) AS min_a, COUNT(*) AS count_all FROM tableName WHERE name LIKE ${name_pattern}
        
        -- Example 4: Query with a table alias.
        SELECT  t.name as name FROM tablename t WHERE id=${id_card}
        
        -- Example 5: Expression calculation and multi-condition query.
        SELECT (a+b) as sum_ab, (b+c) as sum_bc FROM tablename WHERE id=${id_card} and b>=${num} and c<=${num1}
        
        -- Example 6: Grouping with CASE statistics.
        SELECT category, SUM(CASE WHEN name LIKE ${name_pattern} THEN 1 ELSE 0 END) AS proj_score FROM table WHERE id=${id} GROUP BY category
      • Get/List Advanced SQL Examples:

        -- Supported MyBatis tags: if, choose, when, otherwise, trim, foreach, and where.
        -- SQL parameters within tags can be identified with a $ or # symbol, as shown in the examples below.
        
        -- Example 1: Use <where> and <if> to implement conditional filtering.
        SELECT id, name, age 
        FROM tableName
        <where>
          <if test="name != null and name != ''">
            AND age &gt; #{age}
          </if>
          <if test="name == null">
            AND age &lt; #{age}
          </if>
        </where>
          
        -- Example 2: Use <choose> to implement mutually exclusive conditions.
        SELECT id, name, age 
        FROM tableName
        <where>
          <choose>
            <when test="name != null and name != ''">
              AND age &gt; #{age}
            </when>
            <when test="age != null">
              AND age &lt; #{maxAge}
            </when>
            <otherwise>
              AND status = 'active'
            </otherwise>
          </choose>
        </where>
        
        -- Example 3: Use <foreach> to implement an IN query.
        SELECT id, name 
        FROM tableName
        <where>
          id IN
          <foreach item="item" index="index" collection="idList" open="(" separator="," close=")">
            #{item}
          </foreach>
        </where>
        
        -- Example 4: Use <trim> for a custom prefix (as a replacement for <where>).
        SELECT id, name, age 
        FROM ${tableName}
        <trim prefix="WHERE" prefixOverrides="AND | OR ">
          <if test="name != null">
            AND name LIKE #{namePattern}
          </if>
          <if test="minAge != null">
            AND age &gt;= #{minAge}
          </if>
          <if test="status != null">
            AND status = #{status}
          </if>
        </trim>
        
        -- Example 5: Dynamic field query (var_cols).
        SELECT category,${var_cols_metrics} FROM tableName WHERE id = ${id} GROUP BY category

      Format

      Formats the SQL statement for better readability. This is only supported for basic SQL.

      Field reference

      The Field Reference panel displays all fields from the selected data table.

      • Copy: Allows you to copy the table name, all table fields, or a single field.

      • Quick Insert: Click Quick Insert to insert a SQL script template based on the operation type. For details on the script templates, see Quickly import an API SQL script.

      • Fields with issues are marked with a warning image icon. Check whether the service unit to which the field belongs has been published to the production environment or if the service unit still exists.

    2. Click Parse Parameters. Dataphin automatically parses the input and output parameters from the API SQL and adds them to the Request Parameters and Response Parameters sections. If the SQL mode is set to Advanced SQL, you can select Keep Manual Configurations. When you modify the SQL script and need to parse parameters again, the system retains the parameter information you have already entered. You must manually delete any unnecessary parameters. This feature is useful for complex SQL statements where parameters cannot be parsed automatically and must be entered manually.

      Note
      • If the SQL mode is advanced SQL, parameters that start with var_cols are dynamic parameters. You can use these parameters to dynamically specify the fields that are returned by an SQL query. You can add all supported fields to the response parameters. When you call the API, pass the fields that you want to query in the dynamic parameters. If you do not pass any fields, the values of these fields in the response parameters are null.

      • If the SQL mode is Basic SQL and a parameter is optional and no input is provided, the system automatically rewrites the SQL to ignore the corresponding filter condition. If the parameter value type is between, the parameter is required.

      • Because advanced SQL statements can be complex, the SQL parser might not identify all parameters correctly. You may need to add or delete request and response parameters manually.

      Parameter

      Description

      Request parameters

      Parameter name

      The externally visible parameter name. This name is parsed from the SQL and cannot be modified.

      Parameter type

      Required. Select the data type of the field to which the parameter is bound. Supported types are DOUBLE, FLOAT, STRING, DATE(yyyy-MM-dd HH:mm:ss), BOOLEAN, INT, LONG, SHORT, BYTE, BIGDECIMAL, and BINARY.

      If the logical table's field type is not listed, we recommend selecting String.

      Parameter value type

      Required. Select the type of the parameter value. Single value and multiple values are supported.

      • Single Value: The input parameter is parsed as a single value. Applicable operators are =, like, >=, <=, >, <, !=, between.

      • Multiple Values: The input parameter is parsed as multiple values separated by commas (,). The applicable operator is in.

      Parameter processing

      Required for the LIKE operator. If no option is selected, you must manually add wildcards to the input parameter. Supported options are Fuzzy Match (%keyword%), Right Match (%keyword), and Left Match (keyword%).

      Example

      Enter an example value for the parameter to help developers understand it. The example can be up to 1,000 characters long.

      Description

      Enter a description for the parameter. The description can be up to 1,000 characters long.

      Required

      Specifies whether the request parameter is required for API calls.

      • Select No: The SQL statement to call the API can be executed even if this parameter is not included.

      • Select Yes: The SQL statement that calls the API cannot be executed if it does not contain this parameter.

      For example, assume the request parameter is id and it is required, and the response parameter is name. The following statements will have different results:

      • Returns the corresponding name field and data: select name from tableA where id=5;

      • The SQL statement fails to execute: select name from tableA;

      Actions

      • You can batch modify the Parameter Type, Parameter Value Type, Parameter Processing (only available for the LIKE operator), and Required fields of request parameters. You can also batch delete request parameters (in advanced SQL mode only).

      • When Advanced SQL mode is selected, you can click Add Request Parameter to add a parameter manually.

      Response parameters

      Parameter name

      The externally visible parameter name. This name is parsed from the SQL and cannot be modified.

      Parameter type

      Required. Select the data type of the field to which the parameter is bound. Supported types are DOUBLE, FLOAT, STRING, DATE(yyyy-MM-dd HH:mm:ss), BOOLEAN, INT, LONG, SHORT, BYTE, BIGDECIMAL, and BINARY.

      If the logical table's field type is not listed, we recommend selecting String.

      Example

      Enter an example value for the parameter to help developers understand it. The example can be up to 1,000 characters long.

      Description

      Enter a description for the parameter. The description can be up to 1,000 characters long.

      Actions

      • You can batch modify the Parameter Type of response parameters. You can also batch delete parameters (only available in advanced SQL mode).

      • When Advanced SQL mode is selected, you can click Add Response Parameter to add a parameter manually.

    3. Click SQL test run. In the Request Parameter Input dialog box, select the Parameter Type, Parameter Value Type, and Parameter Processing, enter a Test Run Input Value, and then click Confirm.

      • Run Log: Shows the actual SQL statement executed during the SQL test run.

      • Test Run Input Value: Provide a value for the bound field. You can view field values in the Data Preview panel.

      • Batch Operations: Allows you to batch modify the Parameter Type, Parameter Value Type, and Parameter Processing (only available for the LIKE operator) of request parameters. You can also batch delete parameters (only available in advanced SQL mode).

    4. Click Fill in Sample Parameter Values to populate the request and response parameters with values from the last successful test run. Existing sample values are not overwritten, but you can modify them.

    5. This feature is available only when the SQL mode is Advanced SQL and a test run has been recorded. Click Fill in Response Parameters/Import from Test Run Result. In the Fill Parameters dialog box, configure how parameters are added and how to handle parameters with the same name.

      • Add Method: The strategy for adding imported parameters. You can choose to append new parameters or replace all existing parameters.

        • Append New Parameters: Keeps the existing parameters in the response parameter list and appends new, uniquely named parameters parsed from the test run result.

        • Replace All Existing Parameters: Replaces all existing parameters in the response parameter list with the parameters parsed from the test run result.

      • Same-name Parameter Handling: This is available when the Add Method is set to Append New Parameters. It defines the strategy for handling duplicate parameter names. You can choose to keep the existing parameter or replace it.

        • Keep Existing: Retains the original parameter information without changes.

        • Replace: If a parameter from the test run result has the same name as an existing parameter, the existing parameter's type and sample value are updated with those from the test run. If the value from the test run is empty, no replacement occurs.

      If you select Synchronously fill sample values for request parameters, the sample values in the request parameter list are replaced according to the Fill Parameters configuration.

    6. Associated row-level permissions are displayed only when the SQL mode is Basic SQL. Click Parse Parameters, and the system automatically parses the row-level permission information associated with the data source table, including the permission name, description, control field, data source environment, associated table, and associated field. You can also perform the following actions:

      • Enable or Disable row-level permission: This controls whether the permission is active and whether the permission list is visible when you view, compare versions of, or debug/test the API.

      • Create row-level permission: The user must have permission to create row-level permissions. Clicking this takes you to the row-level permission creation page in Management Center > permission management, where you can create a new row-level permission.

        Note
        • You must purchase the row-level permission value-added service to use this feature.

        • The data returned by this API is controlled by row-level permissions. Different permissions can result in different data.

        • In Basic mode, permissions for production tables are displayed. In Dev-Prod mode, permissions for both development and production tables are displayed.

    7. You must purchase the Data Security feature to view the list of associated data masking rules. Click Parse Parameters, and the system automatically parses the data masking rules that are matched by the API fields. The parsed information includes the table name, matched field, category, field sensitivity level, data masking rule name, masking algorithm, and asset source. You can also perform the following actions:

      • Enable or Disable a data masking rule: This controls whether the rule is active and whether data is masked during API debugging or testing.

      • View: Click to go to the table details page in the asset inventory to view the field's classification and sensitivity level details.

      • Manage data masking rules: Click to go to the data masking rules page in Governance > Data Security to create or manage rules. If a field is not associated with a specific rule, the rule name is displayed as Default desensitization policy.

      Note
      • Associated data masking rules are visible only for MySQL, Oracle, and SAP HANA data sources that have a metadata collection task configured.

      • If an application is on the masking whitelist, data is not masked when that application calls the API.

      • Matched fields in the API response are masked according to the specified algorithm.

  2. Click Submit. The system verifies that the API's referenced fields exist in the specified data source. If verification is successful, the API is created.

Next steps

  • After you generate an API, test and publish it to the data service market so that it can be called by applications. For more information, see Test and publish an API.

  • For API deletion, version management, or ownership transfer, see View and manage APIs.