Create an API in SQL mode (Service Unit)
SQL mode lets you create an API by writing SQL queries against a service unit. This topic describes how to create an API in SQL mode.
Prerequisites
To create an API from a service unit, you must first create the service unit. For more information, see Create a service unit.
Limitations
If you call a LIST API whose data source supports pagination, you can use the
PageStartandPageSizeparameters for pagination, regardless of whether paginated query is enabled.If you use a
LIMITclause in the SQL script to specify the number of results to return, thePageStartandPageSizeparameters are ignored. The number of results specified by theLIMITclause is returned.If you use a
LIMITclause in a basic SQL script to restrict the number of results, paginated query is not supported.
Permissions
Project administrators and developers of the service can create APIs.
Usage notes
An API's request and response parameters must come from the same service unit (either a single-table or multi-table service unit). Otherwise, the API cannot be called.
When you write SQL statements based on a service unit, only MySQL syntax is supported. Other SQL dialects are not supported.
Step 1: Choose a creation method
On the Dataphin homepage, choose Services > API Development from the top menu bar.
In the upper-left corner, select a project. In the left-side navigation pane, click API Service. On the API page, click + New API.
In the New API dialog box, select Service Unit API-SQL Mode.
Step 2: Configure API parameters
On the New API page, configure the API's basic information and parameters.
Basic API information
Parameter
Description
API Name
Enter a name for the API. The name must meet the following requirements:
Can contain Chinese characters, letters, digits, and underscores (_).
Must be 4 to 100 characters in length.
Must start with a letter.
Must be globally unique.
Operation Type
The API operation type. Valid values: GET and LIST.
GET: Requests a specific resource from the server.
LIST: Requests a collection of resources from the server.
Data Update Frequency
Specifies the update frequency of the data returned by the API, which helps callers understand how up-to-date the data is. 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 the group to which the API belongs. To create a group, see Create a service group.
Result Pagination
When the request method is LIST, you can enable result pagination. If enabled, you must specify a sort field to ensure a consistent query order and prevent duplicate or missing data between pages. If disabled, the pagination parameters (
PageStartandPageSize) are not displayed on the API debugging or testing page. You can clear the Hide Parameters checkbox to display them.Sort Priority
You can set the sort priority to either the SQL script or the OrderByList request parameter.
SQL script: If a sort order is specified in the SQL script, the
OrderByListcommon 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
OrderByListcommon request parameter take effect. TheOrderByListparameter has a higher priority than the sort settings defined in the API.
Description
Enter a brief description of the API. The description can be up to 128 characters long.
Protocol
The protocol for the data API. HTTP and HTTPS are supported.
HTTP: The HyperText Transfer Protocol (HTTP) is the most widely used network protocol.
HTTPS: If the API gateway is configured as an Alibaba Cloud API Gateway (a dedicated instance or shared instance), you can select HTTPS. Make sure that the SSL certificate for the custom domain name is valid to prevent call failures. To configure an SSL certificate, choose Platform Management Network Configuration to go to the Network Configuration page.
Timeout
The maximum duration for an API call. The default is 3 seconds. You can set this to an integer from 3 to 60.
If an API call exceeds the specified timeout, it fails with an error, which allows for prompt exception handling. For more information about how to view exceptions, see View and manage O&M and monitoring APIs.
Cache settings
You can Enable or Disable this feature. If enabled, you must configure the Cache duration. The default is 300 seconds. You can set it to an integer between 60 and 1,000,000 seconds (approximately 277.78 hours).
Version
Enter the API version number. Each configuration has a version number for comparison with the previous version. The version number must be unique for this API. The version must meet the following requirements:
Up to 64 characters.
Can contain uppercase and lowercase letters, digits, underscores (_), periods (.), and hyphens (-).
Return Type
JSON by default.
Return SQL
Controls whether the API response includes the actual SQL statement that was executed.
Select Yes (Enabled): The API response includes the physical SQL statement executed by the database.
Select No (Disabled): The API response shows the original SQL script.
API request and response parameters
When configuring API request parameters and response parameters, you must first determine the source of the input and output parameters (the service unit). Then, write the API SQL script and parse the request parameters and response parameters. Finally, configure the basic information for the request and response parameters.
In the Parameter Configuration area, after you select the Mode and service unit, the system displays all fields from the selected service unit. You can use these fields as a reference when writing the API SQL script.

Parameter
Description
Mode
Supports Basic and Dev_Prod modes.
In Basic mode, the production environment is read during development, submission, and publishing.
In Dev-Prod mode, the development environment is read during development and submission, and the production environment is read after publishing.
Corresponding fields of service unit
You can copy all fields or a single field. A warning
icon indicates an invalid field. This can occur if the field's service unit has not been published to the production environment, or if the service unit no longer exists.Actions
Data Preview: Click to open the Data Preview panel. The system returns the first 100 rows of data from the current service unit by default. You can choose to return 10, 50, 100, 500, or 1000 rows.
View row-level permission: This action is available when row-level permission is enabled for the referenced service unit. Click to open the View row-level permission panel, which displays information about the row-level permissions associated with the selected service unit, including the permission name, description, control fields, associated tables, and associated fields.
If the mode is Basic, the row-level permissions for the service unit in the production environment are displayed. If the mode is Dev-Prod, the permissions for the service units in both the development and production environments are displayed.
Write the API SQL script according to the following rules and examples:
When you create an API from a service unit, the SQL script must follow MySQL syntax.
The following are not supported:
Multiple SQL statements.
Non-
SELECTstatements, such asINSERT,UPDATE,CREATE, andDELETE.Multi-table joins and nested queries.
Using an alias for the query table.
If you use an aggregate function such as
Min,Max,Sum, orCount, you must assign an alias, which will be used as the response parameter name. For example:sum(num) as total_num.
The SQL script template that Dataphin can parse for response parameters and request parameters is as follows:
Template 1: Query and return fields from a service unit.
Syntax
select <response_parameter> from <service_unit_name> where <request_parameter>=${request_parameter_value}Example
-- Query for id_card and name from service_unit_a where c equals id_card. select id_card,name from service_unit_a where c=${id_card}
Template 2: Query and return fields from a service unit by using an
INclause.Syntax
select <response_parameter> from <service_unit_name> where <request_parameter> in (${request_parameter_value})Example
-- Query for id_card and name from service_unit_a where c is in the id_card list. select id_card,name from service_unit_a where c in (${id_card})
Template 3: Use
MAX,SUM,MIN, andCOUNTaggregate functions. Also supportsLIKEfor fuzzy matching.Syntax
select max(<response_parameter_1>) as <alias_c>,sum(<response_parameter_1>) as <alias_b> ,min(<response_parameter_1>) as <alias_d>,count(*) as <alias_e> from <service_unit_a> where <request_parameter_1> like ${request_parameter_value_1}Example
-- In service_unit_a, query for records where c is like id_card. -- Return the maximum value of field a as c, the sum of a as b, the minimum of a as d, and the total count as e. select max(a) as c,sum(a) as b ,min(a) as d,count(*) as e from service_unit_a where c like ${id_card}
Template 4: Field operations support
+(addition),-(subtraction),*(multiplication),/(division),%(modulo),//(integer division), and**(power). Logical operatorsANDandORare also supported.Syntax
select (<response_parameter_1>+<response_parameter_2>) as <alias>, (<response_parameter_2>+<response_parameter_3>) as <alias> from <service_unit_a> where <field_c>=${request_parameter_1} and <field_b>>=${request_parameter_2} or <field_c><=${request_parameter_3}Example
-- In service_unit_a, find records where c equals id_card, b is greater than or equal to num, or c is less than or equal to num1. -- Return the sum of a and b as acd, and the sum of b and c as bcf. select (a+b) as acd, (b+c) as bcf from service_unit_a where c=${id_card} and b>=${num} or c<=${num1}
ImportantIn the four templates above, the API's request and response parameters must come from the same service unit (either a single-table or multi-table service unit). Otherwise, the API cannot be called.
Click Parse Parameters. Dataphin automatically parses the parameters from the SQL script and adds them to the Request Parameters and Response Parameters sections. The basic settings for request and response parameters are similar. The following table describes this information and what you need to configure.
Parameter
Description
Parameter Name
The parameter name exposed to API callers.
Parameter Type
The data type of the parameter. Supported types include DOUBLE, FLOAT, STRING, DATE(yyyy-MM-dd HH:mm:ss), BOOLEAN, INT, LONG, SHORT, BYTE, BIGDECIMAL, and BINARY. The selected type must match the data type of the corresponding field in the service unit.
The field type of the service unit must be consistent with the field type of the request parameter. You can select the corresponding field type.
Parameter value type
Select the value type of the parameter. Supported types are single value and multiple values.
single value: The parameter accepts a single value. This is used with operators such as
=, like, >=, <=, >, <, !=, between.multiple values: The parameter accepts multiple comma-separated values. This is used with the
inoperator.
Parameter Processing
This setting is required when the operator is
LIKE. If you do not select a processing method, you must manually include wildcards in the parameter value. You can select Fuzzy Match (%keyword%), Right Match (keyword%), or Left Match (%keyword).Example
Enter example values for the request and response parameters to help developers understand their usage. The examples can be up to 1,000 characters long.
Description
Enter a brief description for the request and response parameters. The description can be up to 1,000 characters long.
Required
Specify whether this request parameter is required.
Select No: The API call can be executed even if the parameter is not included in the statement.
Select Yes: This parameter must be included in API calls.
For example, if
idis a required request parameter andnameis a response parameter, executing the following statements produces different results:select name from tableA where id=5;: Returns the correspondingnamefield and data.select name from tableA;: The SQL statement execution fails.
Actions
You can perform the following batch operations on request and response parameters:
Request Parameters: You can batch modify the parameter type, parameter value type, parameter processing (only when the operator is
LIKE), and required status of request parameters.Response Parameters: You can batch modify the parameter type of response parameters.
Click SQL Trial Run. In the Request Parameter Input dialog box, select the Parameter Type, Parameter value type, Parameter Processing, and Trial Run Input Value, and then click Confirm.
Run Log: You can view the actual SQL statement executed during the trial run.
Trial Run Input Value: You need to provide a value for the bound field. You can view field values in the Data Preview panel.
Batch Operations: You can batch modify the parameter type, parameter value type, and parameter processing (only when the operator is
LIKE) of request parameters.
Click Fill Parameter Example Values. The system populates the request and response parameters with the example values from the last successful trial run. If a parameter already has an example value, it is not overwritten. You can modify the values manually.
Click Submit. The system verifies that the API's referenced fields exist in the specified service unit. If the verification is successful, the API is created.
Next steps
After you create an API, you need to test it and publish it so that it can be called by applications. For more information, see Test and publish an API.
To delete an API, manage its versions, transfer ownership, or perform other management operations, see View and manage APIs.