Create an API in SQL mode (dataset)

Updated at:

You can create flexible APIs from datasets by writing SQL statements. This method supports features such as parameterized queries and vector queries. This topic describes how to create an API in SQL mode.

Prerequisites

  • You must subscribe to the unstructured data and Data Service features to use dataset APIs.

  • You have created and submitted a dataset in R&D > Data Development > Dataset. For more information, see Create and manage datasets.

Limits

  • When you use a paginated query for an API, you must specify a sort order for fields to ensure stable results. This prevents duplicate or missing records across pages. The pagination parameters (PageStart and PageSize) are displayed on the API debugging and testing pages only when paginated queries are used.

  • During an API call, you can use the PageStart and PageSize parameters for pagination, regardless of whether a paginated query is enabled for the API.

  • Only table datasets and hybrid datasets support creating APIs in SQL mode.

  • APIs created from datasets in SQL mode support only synchronous calls and single-table queries. Join queries are not supported, and the system does not validate whether the specified fields exist in the dataset.

Permissions

Project administrators and developers of Data Service can create APIs.

Step 1: Choose a method to create an API

  1. In the top navigation bar of the Dataphin homepage, choose Service > API Development.

  2. In the upper-left corner, select a project. In the left-side navigation pane, click API Service. On the API page, click + Create API.

  3. In the Create API dialog box, select Dataset API-SQL Mode (dataset).

Step 2: Configure API parameters

  1. On the Create API page, configure the basic information and SQL parameters for the API.

    Basic information

    Parameter

    Description

    API name

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

    • It can contain only letters, digits, underscores (_), and Chinese characters.

    • It must be 4 to 100 characters in length.

    • It must start with a letter.

    • It must be globally unique.

    Operation mode

    The operation mode of the API. Valid values: GET and LIST.

    • GET: Requests a specific resource from the server.

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

    Data update frequency

    Specifies the update frequency of the data returned by the API, which helps callers understand the data's timeliness. Supported frequencies are Daily, Hourly, Per Minute, and Custom. If you select Custom, you can enter a string of up to 128 characters.

    API group

    Select an API group configured in the current project. To create one, see Create a service group.

    Description

    Enter a brief description of the API. The description can be up to 128 characters in length.

    Protocol

    The interface protocol for the API. Only HTTP is supported.

    HTTP: HyperText Transfer Protocol (HTTP) is the most widely used network protocol.

    Invocation mode

    Defines the communication mode between the client and server. Only synchronous call is supported.

    synchronous call: With a synchronous call, a client sends a request and must wait for the server's response before sending another one. For complex queries, this can lead to long response times and occupy server connections, increasing server load. This mode is suitable for scenarios that require high real-time performance and short processing times.

    Timeout

    The maximum duration allowed for an API call. The default is 3 seconds. You can set it to an integer from 3 to 60 seconds.

    If an API call exceeds the configured timeout, the call fails with an error. This helps you promptly identify and handle API call exceptions. To view exceptions, see Manage O&M and monitoring APIs.

    Maximum rows returned

    This parameter is available when the Operation mode is LIST. The maximum number of rows that can be returned is 10,000. You can enter an integer from 1 to 10,000.

    Cache settings

    Select Enable or Disable. If you enable caching, you must configure the Cache Duration. The default value is 300 seconds. You can set an integer from 60 to 1,000,000 (approximately 277.78 hours).

    Version number

    Enter a version number for the API. Version numbers help distinguish different configurations of the same API. The version number must be unique within the API. The version number must follow these rules:

    • It must be no more than 64 characters in length.

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

    Return type

    The format of the API response. The default and only supported type is JSON.

    Return SQL

    Controls whether the executed SQL statement is included in the API response.

    • Select Yes (Enabled): The API response includes the SQL statement that was executed on the database.

    • Select No (Disabled): The API response includes the original SQL script.

  2. Select a dataset and write SQL

    In the Parameter Configuration section, select a dataset and then write an SQL statement to define the API's query logic.

    1. Select a dataset: Configure the Mode, Project, Dataset, and version.

      Parameter

      Description

      Mode

      Basic mode and SQL mode are supported. In Basic mode, development and submission operations read from the production database. In SQL mode, you write SQL statements to flexibly define the API query logic.

      SQL mode

      You can select either Basic SQL or Advanced SQL mode.

      • Basic SQL: Write query logic by using basic SQL syntax. For example SQL, see Examples.

      • Advanced SQL: Write query logic by using SQL syntax that supports MyBatis tags. The supported tags are: if, choose, when, otherwise, trim, foreach, and where. For example SQL, see Examples.

      Project

      Select a project in the corresponding mode.

      Dataset

      Select a published dataset and its version from the project.

      Result pagination

      Pagination is available when the Operation mode is LIST. If you enable this feature, you must specify sort fields to ensure stable query results and prevent duplicate or missing records across pages. If you disable this feature, the pagination parameters (PageStart and PageSize) are hidden on the API debugging or testing page, but you can choose to display them.

      Sort priority

      You must set the sort priority if you enable result pagination.

      • If SQL mode is set to Basic SQL, you can choose the sort priority between the SQL script and the OrderByList request parameter.

        • SQL script: If a sort order is specified in the SQL script, the OrderByList common request parameter is ignored.

        • OrderByList request parameter: When you test or debug the API, both the sort order defined in the SQL script and the OrderByList common request parameter take effect. The OrderByList parameter has a higher priority than the sort settings defined in the API.

      • If SQL mode is set to Advanced SQL, both the sort order defined in the SQL script and the OrderByList common request parameter take effect when you test or debug the API. The OrderByList common request parameter has a higher priority than the sort settings defined in the API.

    2. Write an SQL statement: In the SQL editor, write a query statement. The SQL editor supports the following features:

      • API SQL script editing: Helps you adhere to SQL editing standards when you write scripts. For more information, see API SQL script editing instructions.

      • Syntax highlighting: SQL keywords, table names, and field names are highlighted in different colors for readability.

      • Format: Click the format button in the toolbar to automatically format the SQL statement.

      • Parameterized query: Use the ${parameter_name} syntax to define request parameters. The system automatically parses these placeholders and generates a corresponding list of request parameters. A parameter name must start with a letter, be 1 to 64 characters long, and contain only letters, digits, and underscores (_).

      Examples

      Get/List basic SQL examples:
      -- Example 1: Query a single record based on a condition. If the 'id' parameter is optional and not provided, the condition is automatically ignored.
      SELECT id,name FROM tablename WHERE id = ${id}
      
      -- Example 2: Perform a batch query with 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: Query with expression calculation and multiple conditions.
      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 + CASE statement for counting.
      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 include: if, choose, when, otherwise, trim, foreach, and where.
      -- SQL parameters within tags can be identified by the $ or # symbol, as shown in the following examples.
      
      -- Example 1: Use <where> and <if> for 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> for 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> for 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> to customize prefixes (alternative to <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
      Note
      • The table names in the SQL statement must match those defined in the dataset.

      • The SQL syntax must be compatible with the engine of the table associated with the dataset. You can view the Engine type in the Field Reference panel on the right.

      • In SQL statements that involve vector distance calculations, special operators must be wrapped in CDATA syntax. For example, to sort by cosine similarity for a vector, write the statement as ORDER BY embedding <![CDATA[<=>]]> '[1,2,3]'.

    3. Field reference

      After selecting a dataset, click Field Reference on the right to view its fields. The panel provides the following information:

      • Table name: The names of the tables included in the dataset. You can quickly copy a table name to the SQL editor.

      • Engine type: The engine type of the dataset.

      • Field list: Displays the names and types of all fields in each table. You can click a field name to insert it into the SQL editor. URL fields are marked with a link icon, and vector fields are marked with a vector icon.

    4. Request parameters

      After you write the SQL statement, click Parse parameters. The system automatically parses the ${parameter_name} placeholders in the SQL and generates a list of request parameters. If you select Advanced SQL mode, you can select the Keep manual configurations checkbox. When you modify the SQL script and parse parameters again, the system retains the information that you have entered. You must manually delete any unnecessary parameters. This is useful for complex SQL statements where parameters cannot be parsed and must be entered manually.

      Note
      • In Advanced SQL mode, parameters starting with var_cols are dynamic parameters. They allow you to specify at runtime which fields the SQL query returns. You can add all supported fields to the response parameters. When calling the API, pass the required fields in the dynamic parameter. If no fields are passed, their corresponding values in the response will be null.

      • In Basic SQL mode, if a parameter is optional and no value 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.

      • Advanced SQL statements can be complex, and the parameters parsed by the SQL compiler may not be complete or correct. Therefore, you may need to manually add or delete request and response parameters to match your SQL logic.

      Parameter

      Description

      Request parameters

      Parameter name

      Automatically parsed from ${parameter_name} in the SQL. You can manually modify the name. The name must follow these rules:

      • The parameter name must be unique.

      • It must contain only letters, digits, or underscores (_).

      • It must start with a letter.

      • It must be 1 to 64 characters in length.

      Parameter type

      Displays the corresponding field type from the dataset.

      Parameter types include double, float, string, Date(yyyy-MM-dd HH:mm:ss), Boolean, int, long, short, byte, BigDecimal, and binary.

      Parameter value type

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

      • Single value: The input parameter is parsed as a single value based on the parameter type.

      • Multiple values: The input parameter is parsed as multiple values separated by commas (,). This is typically used with the SQL in operator.

      Parameter processing

      This setting is required in Basic SQL mode when a vector field is of the string type and the parameter value type is single value. You can select Platform vectorization or No processing.

      • Platform vectorization: The system automatically calls the embedding model configured for the vector field to convert the input text into a vector.

      • No processing: The system saves the submitted data as is, without performing any vector conversion or semantic analysis.

      Example

      Enter an example value for the request parameter to help developers understand its usage. The example can be up to 1,000 characters in length.

      Description

      Enter a brief description of the request parameter. The description can be up to 1,000 characters in length.

      Required

      Specifies whether this parameter is required in an API call.

      • Select No: The API can be called even if this parameter is omitted from the request.

      • Select Yes: The API call will fail if this parameter is not included in the request.

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

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

      • Results in an error: select name from tableA;.

      Default value

      The value used if the parameter is omitted from an API call. If no default value is configured, the value is treated as null. The default value can be up to 1,000 characters in length.

      Response parameters

      Parameter name

      Required. The publicly exposed parameter name. It is parsed from the SQL and cannot be modified.

      Parameter type

      The data format for API calls. Parameter types include double, float, string, Date(yyyy-MM-dd HH:mm:ss), Boolean, int, long, short, byte, BigDecimal, binary, and vector.

      Example

      Enter an example of the response parameter value to help developers understand its usage. The example can be up to 1,000 characters in length.

      Description

      Enter a brief description of the response parameter. The description can be up to 1,000 characters in length.

    5. SQL dry run

      Click SQL dry run. In the Request Parameters dialog box, specify the parameter type, parameter value type, parameter processing, and dry run input value, and then click Confirm.

      • Run log: View the actual SQL statement executed during the SQL dry run.

      • Dry run input value: You must provide input values for the request parameters to perform a dry run. You can view the field values in the data preview panel.

      • Batch operations: You can batch modify the parameter type, parameter value type, and parameter processing (available only in Basic SQL mode for string-type vector fields with a single value type) of request parameters, or batch delete parameters (available only in Advanced SQL mode).

    6. Fill parameter example values

      • Click Fill parameter example values. The system populates the request and response parameters with the example values from the last successful dry run. Existing example values are not overwritten. You can modify the populated values.

      • This feature is available only in Advanced SQL mode when a dry run record exists. Click Fill response parameters/Import from dry run result. In the dialog box that appears, configure the Add method and Handling of parameters with the same name.

        • Add method: Defines how to import parameters from the dry run result. Append new parameters and Replace all existing parameters are supported.

          • Append new parameters: Retains existing parameters in the response parameter list and appends new parameters parsed from the dry run result. Only parameters with unique names are added.

          • Replace all existing parameters: Replaces all existing parameters in the response parameter list with the parameters parsed from the dry run result.

        • Handling of parameters with the same name: This setting is available when the Add method is Append new parameters. It defines the strategy for handling duplicate parameter names. Keep existing and Replace are supported.

          • Keep existing: Keeps the original parameter information unchanged.

          • Replace: If a parameter name from the dry run result already exists in the list, the system updates the parameter's type and example value with those from the dry run result. If the example value from the dry run is empty, the existing example value is not overwritten.

      If you select Synchronously fill example values for request parameters, the example values in the request parameter list are replaced based on the fill settings.

    7. Download URL field configuration

      If the data source is OSS, Amazon S3, or OBS and the fields returned by the SELECT statement include a URL field, the system automatically generates a temporary download link and includes it in the API response. You can configure the domain name replacement and expiration time.

      • Domain name replacement: If you enable this, enter the domain name to use for replacement. If disabled, the default domain name of the file storage service is used.

      • Expiration time: The expiration time of the link. The default is 3,600 seconds. You can set a value from 60 to 86,400 seconds (24 hours).

  3. Click Submit to create the API.

Next steps

  • After you create an API, you need to test it and publish it to the Data Service marketplace, which makes it available for applications to call. For more information, see Test and publish an API.

  • To perform operations such as deleting an API, managing versions, or transferring ownership, see Manage an API.