Updated on 2026-10-27 GMT+08:00

Creating a Function

Function

This API is used to create a function.

Calling Method

For details, see Calling APIs.

Authorization Information

Each account has all the permissions required to call all APIs, but IAM users must be assigned the required permissions. For details about the required permissions, see Permissions Policies and Supported Actions.

URI

POST /v2/{project_id}/fgs/functions

Table 1 Path Parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Parameter description:

Project ID. For details, see Obtaining a Project ID.

Constraints:

None

Value range:

32 characters, including letters and digits.

Default value:

None

Request Parameters

Table 2 Request header parameters

Parameter

Mandatory

Type

Description

X-Auth-Token

Yes

String

Parameter description:

User token.

The token can be obtained by calling the IAM API. The value of X-Subject-Token in the response header is the user token.

Constraints:

None

Value range:

None

Default value:

None

Content-Type

Yes

String

Parameter description:

Specifies the type (or format) of the message body.

Constraints:

None

Value range:

Only application/json is supported.

Default value:

application/json

Table 3 Request body parameters

Parameter

Mandatory

Type

Description

func_name

Yes

String

Parameter description:

Function name.

Constraints:

The value can contain letters, digits, underscores (_), and hyphens (-). It must start with a letter and end with a letter or digit.

Value range:

[1, 60]

Default value:

None

package

Yes

String

Parameter description:

Group to which the function belongs. This field is defined to group functions.

Constraints:

None

Value range:

None

Default Value:

default

runtime

Yes

String

Parameter description:

Runtime of a FunctionGraph function, that is, the function execution environment.

Constraints:

None

Value range:

  • Java8: Java 8

  • Java11: Java 11

  • Java17: Java 17

  • Java21: Java 21

  • Python2.7: Python 2.7

  • Python3.6: Python 3.6

  • Python3.9: Python 3.9

  • Python3.10: Python 3.10

  • Python3.12: Python 3.12

  • Go1.x: Go 1.x

  • Node.js6.10: Nodejs 6.10

  • Node.js8.10: Nodejs 8.10

  • Node.js10.16: Nodejs 10.16

  • Node.js12.13: Nodejs 12.13

  • Node.js14.18: Nodejs 14.18

  • Node.js16.17: Nodejs 16.17

  • Node.js18.15: Nodejs 18.15

  • Node.js20.15: Nodejs 20.15

  • C#(.NET Core 2.1): C# 2.1

  • C#(.NET Core 3.1): C# 3.1

  • C#(.NET Core 6.0): C# 6.0

  • C#(.NET Core 8.0): C# 8.0

  • Custom: custom runtime

  • PHP7.3: Php 7.3

  • PHP8.3: Php 8.3

  • Cangjie1.0

  • Cangjie0.52.3

  • HTTP

Custom image-based functions

Default Value:

None

timeout

Yes

Integer

Parameter description:

Function execution timeout. If the execution times out, the function will be forcibly stopped. Unit: second

Constraints:

None

Value range:

[3, 259200]

Default Value:

3

handler

Yes

String

Parameter description:

Handler of the function.

For example, for Node.js function myfunction.handler, the file name is myfunction.js, and the handler function is handler.

Constraints:

It is in the format of "xx.xx" and must contain a period (.). The handler of a custom image function is a hyphen (-).

Value range:

The value contains 3 to 128 characters.

Default Value:

None

depend_version_list

No

Array of strings

Parameter description:

Dependency versions.

Constraints:

None

Value range:

None

Default Value:

None

func_vpc

No

FuncVpc object

VPC configuration. An agency with VPC permissions must be configured for the function.

memory_size

Yes

Integer

Parameter description:

Memory (MB) consumed by the function.

Constraints:

None

Value range:

  • 128

  • 256

  • 512

  • 768

  • 1024

  • 1280

  • 1536

  • 1792

  • 2048

  • 2560

  • 3072

  • 3584

  • 4096

Default Value:

None

gpu_memory

No

Integer

Parameter description:

GPU memory. This parameter is available only for functions created with a custom runtime or image. The unit is MB.

Constraints:

None

Value range:

  • 1024

  • 2048

  • 3072

  • 4096

  • 5120

  • 6144

  • 7168

  • 8192

  • 9216

  • 10240

  • 11264

  • 12288

  • 13312,

  • 14336

  • 15360

  • 16384

Default Value:

None

code_type

No

String

Parameter description:

Function code type. Options:

Constraints:

None

Value range:

The options are as follows:

inline: inline code

zip: ZIP file

obs: function code stored in an OBS bucket

jar: JAR file, mainly for Java functions

Custom-Image-Swr: The function code comes from the SWR custom image.

Default Value:

None

code_url

No

String

Parameter description:

If CodeType is set to obs, enter the OBS URL of the function code package. If CodeType is not set to obs, leave this parameter blank.

Constraints:

This parameter is valid only when CodeType is set to obs.

Value range:

OBS path

Default Value:

None

code_filename

No

String

Parameter description:

Name of a function file. This parameter is mandatory only when CodeType is set to jar or zip.

Constraints:

This parameter is required when CodeType is set to jar or zip.

Value range:

None

Default Value:

None

custom_image

No

CustomImage object

Parameter description:

Container image.

Constraints:

This parameter is required when CodeType is set to Custom-Image-Swr.

Default Value:

None

user_data

No

String

Parameter description:

Name/Value information defined for the function. These are parameters used in the function. For example, if a function needs to access a host, you can set a custom parameter Host={host_ip}. The total length cannot exceed 4 KB.

Constraints:

None

Value range:

json indicates a character string in JSON format.

Default Value:

None

encrypted_user_data

No

String

Parameter description:

Name/value information to be encrypted.

Constraints:

None

Value range:

Message structure, which is a JSON string.

Default Value:

None

xrole

No

String

Parameter description:

Configuration agency. You need to create an agency on the IAM console.

Constraints:

This parameter is mandatory if the function needs to access other cloud services. After specifying a function configuration agency, you can use the context method in the function handler to obtain a token, an AK, and an SK for accessing other cloud services. No agency is required if FunctionGraph does not access any cloud services.

Value range:

None

Default Value:

None

app_xrole

No

String

Parameter description:

Execution agency. You can optimize performance by configuring a separate agency for function execution, otherwise, the same agency is used for both execution and configuration.

Constraints:

None

Value range:

None

Default Value:

None

description

No

String

Parameter description:

Description of the function.

Constraints:

None

Value range:

None

Default Value:

None

func_code

No

FuncCode object

Response body of the FuncCode structure.

mount_config

No

MountConfig object

Mounting configuration.

initializer_handler

No

String

Parameter description:

Initializer of the function in the format of "xx.xx". It must contain a period (.). ".

For example, for the Node.js function myfunction.initializer, the file name is myfunction.js, and the initialization input is

The interface function name is initializer.

Constraints:

This parameter is mandatory when the initialization function is configured.

Value range:

None

Default Value:

None

initializer_timeout

No

Integer

Parameter description:

Initialization timeout interval. The timeout function will be forcibly stopped.

Constraints:

This parameter is mandatory when the initialization function is configured.

Value range:

[1, 300]

Default Value:

None

pre_stop_handler

No

String

Parameter description:

The pre-stop handler of a function. The value must contain a period (.) in the format of xx.xx. ".

For example, for Node.js function myfunction.pre_stop_handler, the file name is myfunction.js, and the initialization function is pre_stop_handler.

Constraints:

None

Value range:

None

Default Value:

None

pre_stop_timeout

No

Integer

Parameter description:

Initialization timeout interval. The timeout function will be forcibly stopped.

Constraints:

None

Value range:

1 to 90 seconds

Default Value:

None

enterprise_project_id

No

String

Parameter description:

Enterprise project ID.

Constraints:

This parameter is mandatory when an enterprise user creates a function.

Value range:

None

Default Value:

None

type

No

String

Parameter description:

Function Version

Constraints:

The new version supports only v2.

Value range:

  • v2: official version

  • v1: deprecated version.

Default Value:

v2

log_config

No

FuncLogConfig object

Function log configuration.

network_controller

No

NetworkControlConfig object

Network configuration.

is_stateful_function

No

Boolean

Parameter description:

Whether stateful functions are supported. If they are supported, set this parameter to true.

Constraints:

The v2 version is supported.

Value range:

  • true: supported.

  • false: not supported.

Default Value:

false

enable_dynamic_memory

No

Boolean

Parameter description:

Whether to enable dynamic memory allocation.

Constraints:

None

Value range:

  • true: enabled.

  • false: disabled.

Default Value:

false

lts_custom_tag

No

Map<String,String>

Parameter description:

Custom log tag. You can use these tags to filter function logs in LTS.

Constraints:

You need to enable the log function.

Value range:

String mapping pair

Default Value:

None

enable_lts_log

No

Boolean

Definition

Whether to enable logging.

Constraints

N/A

Range

  • true: Yes. If this parameter is set to true and log_config is not passed, FunctionGraph automatically creates a log group and log stream.

  • false: No

Default value

false

user_data_encrypt_kms_key_id

No

String

Definition

ID of the KMS master key used to encrypt environment variables.

Constraints

^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$

Range

[0, 36]

Default value

N/A

code_encrypt_kms_key_id

No

String

Definition

ID of the KMS master key used to encrypt user code.

Constraints

^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$

Range

[0, 36]

Default value

N/A

domain_names

No

String

Definition

Private domain names in a VPC.

Constraints

To call a DNS API to resolve private domain names, specify an agency with the permissions to read DNS resources.

Range

N/A

Default value

N/A

tags

No

String

Definition

Function tag.

Constraints

N/A

Range

N/A

Default value

N/A

Table 4 FuncVpc

Parameter

Mandatory

Type

Description

domain_id

No

String

Parameter description:

Tenant account ID.

Value range:

None

namespace

No

String

Parameter description:

Project ID.

Value range:

None

vpc_name

No

String

Definition:

VPC name

Value range:

None

vpc_id

Yes

String

Parameter description:

VPC ID.

Value range:

None

subnet_name

No

String

Parameter description:

Subnet name.

Value range:

None

subnet_id

Yes

String

Parameter description:

Subnet ID.

Value range:

None

cidr

No

String

Parameter description:

Subnet mask.

Value range:

None

gateway

No

String

Parameter description:

Gateway.

Value range:

None

security_groups

No

Array of strings

Parameter description:

Security Group

Value range:

Character string list

is_safety

No

Boolean

Definition

Whether to enable secure access. When secure access is enabled, you need to configure the VPCEP network to establish a secure VPC connection to private domain names. Once enabled, this feature cannot be disabled.

Range

  • true: Yes

  • false: No

Table 5 CustomImage

Parameter

Mandatory

Type

Description

enabled

No

Boolean

Parameter description:

Whether to use an image. If no image is used, the following parameters do not take effect.

Value range:

true: An image is used.

false: No image is used.

image

No

String

Parameter description:

Image address.

Value range:

None

command

No

String

Parameter description:

Command for starting a container image.

Value range:

None

args

No

String

Parameter description:

Command line parameter for starting a container image.

Value range:

None

working_dir

No

String

Parameter description:

Working directory of an image container.

Value range:

None

uid

No

String

Parameter description:

User ID of an image container.

Value range:

None

gid

No

String

Parameter description:

User group ID of an image container.

Value range:

None

is_public

No

Boolean

Parameter description:

Whether the image is a public image.

Value range:

None

Table 6 FuncCode

Parameter

Mandatory

Type

Description

file

No

String

Parameter description:

Function code, which must be encoded using Base64. If this parameter is left blank, the default code is used.

Value range:

Base64-encoded string.

link

No

String

Parameter description:

Function code URL.

Value range:

OBS link address

Table 7 MountConfig

Parameter

Mandatory

Type

Description

mount_user

Yes

MountUser object

User information.

func_mounts

Yes

Array of FuncMount objects

Parameter description:

Mounted resources.

Value range:

None

Table 8 MountUser

Parameter

Mandatory

Type

Description

user_id

Yes

Integer

Parameter description:

User ID.

Value range:

An integer ranging from -1 to 65534

user_group_id

Yes

Integer

Parameter description:

Group ID

Value range:

An integer ranging from -1 to 65534

Table 9 FuncMount

Parameter

Mandatory

Type

Description

mount_type

Yes

String

Definition

Mount type. This parameter is mandatory when func_mounts is not empty.

Range

  • sfs: SFS Capacity-Oriented

  • sfsTurbo: SFS

  • ecs: ECS

mount_resource

Yes

String

Parameter description:

ID of the mounted resource (cloud service ID). This parameter is mandatory when func_mounts is not empty.

Value range:

None

mount_share_path

No

String

Parameter description:

Remote mount path. For example, 192.168.0.12:/data. This parameter is mandatory if mount_type is set to ecs.

Value range:

Shared path opened by the ECS

local_mount_path

Yes

String

Parameter description:

Function access path. This parameter is mandatory when func_mounts is not empty.

Value range:

Mount directory in the function container. The directory is generally a two-layer structure.

Table 10 FuncLogConfig

Parameter

Mandatory

Type

Description

group_name

No

String

Parameter description:

Name of the log group bound to the function.

Value range:

None

group_id

No

String

Parameter description:

ID of the log group bound to the function.

Value range:

None

stream_name

No

String

Parameter description:

Name of the log stream bound to the function.

Value range:

None

stream_id

No

String

Parameter description:

ID of the log stream bound to the function.

Value range:

None

Table 11 NetworkControlConfig

Parameter

Mandatory

Type

Description

disable_public_network

No

Boolean

Parameter description:

Disable public access.

Value range:

true: public network access is disabled.

false: public network access is allowed.

trigger_access_vpcs

No

Array of VpcConfig objects

Parameter description:

VPC access restriction.

Value range:

None

Table 12 VpcConfig

Parameter

Mandatory

Type

Description

vpc_name

No

String

Parameter description:

VPC name.

Value range:

None

vpc_id

No

String

VPC ID.

Response Parameters

Status code: 200

Table 13 Response body parameters

Parameter

Type

Description

func_id

String

Parameter description:

Function ID, which uniquely identifies a function.

Value range:

None

func_urn

String

Parameter description:

Function URN.

Value range:

None

func_name

String

Parameter description:

Function name.

Value range:

None

domain_id

String

Parameter description:

Domain name ID.

Value range:

None

namespace

String

Parameter description:

Project ID.

Value range:

None

project_name

String

Parameter description:

Project name.

Value range:

None

package

String

Parameter description:

Group to which the function belongs. This field is defined to group functions.

Value range:

None

runtime

String

Parameter description:

Runtime of a FunctionGraph function, that is, the function execution environment.

Value range:

  • Java8: Java 8

  • Java11: Java 11

  • Java17: Java 17

  • Java21: Java 21

  • Python2.7: Python 2.7

  • Python3.6: Python 3.6

  • Python3.9: Python 3.9

  • Python3.10: Python 3.10

  • Python3.12: Python 3.12

  • Go1.x: Go 1.x

  • Node.js6.10: Nodejs 6.10

  • Node.js8.10: Nodejs 8.10

  • Node.js10.16: Nodejs 10.16

  • Node.js12.13: Nodejs 12.13

  • Node.js14.18: Nodejs 14.18

  • Node.js16.17: Nodejs 16.17

  • Node.js18.15: Nodejs 18.15

  • Node.js20.15: Nodejs 20.15

  • C#(.NET Core 2.1): C# 2.1

  • C#(.NET Core 3.1): C# 3.1

  • C#(.NET Core 6.0): C# 6.0

  • C#(.NET Core 8.0): C# 8.0

  • Custom: custom runtime

  • PHP7.3: Php 7.3

  • PHP8.3: Php 8.3

  • Cangjie1.0

  • Cangjie0.52.3

  • HTTP

Custom image-based functions

timeout

Integer

Parameter description:

Function execution timeout. If the timeout is reached, the function will be forcibly stopped.

Value range:

3 to 259,200 seconds

handler

String

Parameter description:

Handler

It is in the format of "xx.xx" and must contain a period (.). The handler of a custom image function is -.

For example, for Node.js function myfunction.handler, the file name is myfunction.js, and the handler function is handler. Can contain a maximum of 128 characters.

Value range:

3 to 128 characters

memory_size

Integer

Parameter description:

Memory (MB) consumed by the function.

Value range:

  • 128

  • 256

  • 512

  • 768

  • 1024

  • 1280

  • 1536

  • 1792

  • 2048

  • 2560

  • 3072

  • 3584

  • 4096

gpu_type

String

Parameter description:

Type.

Value range:

None

cpu

Integer

Parameter description:

CPU resources of a function.

Unit: millicore (1 core = 1000 millicores).

The value of this field is proportional to that of MemorySize. By default, 100 CPU millicores are required for 128 MB memory.

Value range:

None

gpu_memory

Integer

Parameter description:

GPU memory. This parameter is available only for functions created with a custom runtime or image. The unit is MB.

code_type

String

Parameter description:

Function code type

Value range:

The options are as follows:

inline: inline code

zip: ZIP file

obs: function code stored in an OBS bucket

jar: JAR file, mainly for Java functions

Custom-Image-Swr: The function code comes from the SWR custom image.

code_url

String

Parameter description:

If CodeType is set to obs, enter the OBS URL of the function code package. If CodeType is not set to obs, leave this parameter blank.

Value range:

OBS link address

code_filename

String

Parameter description:

Name of a function file. This parameter is mandatory only when CodeType is set to jar or zip.

Value range:

None

code_size

Long

Parameter description:

Code size in bytes.

Value range:

None

domain_names

String

Parameter description:

Private domain name configured for resolution.

Value range:

None

user_data

String

Parameter description:

Name/Value information defined for the function. These are parameters used in the function. For example, if a function needs to access a host, you can set a custom parameter Host={host_ip}. The total length cannot exceed 4 KB.

Value range:

json indicates a character string in JSON format.

encrypted_user_data

String

Parameter description:

Name/value information to be encrypted.

Value range:

Message structure, which is a JSON string.

digest

String

Parameter description:

SHA512 hash value of function code, which is used to determine whether the function is changed.

Value range:

None

version

String

Parameter description:

Function version, which is automatically generated by the system. The version name is in the format of "vYYYYMMDD-HHMMSS" (v+year/month/day-hour/minute/second).

Value range:

None

image_name

String

Parameter description:

Internal identifier of a function version.

Value range:

None

xrole

String

Parameter description:

Configuration agency. You need to create an agency on the IAM console. This field is mandatory when a function needs to access other services. After specifying a function configuration agency, you can use the context method in the function handler to obtain a token, an AK, and an SK for accessing other cloud services. No agency is required if FunctionGraph does not access any cloud services.

Value range:

None

app_xrole

String

Parameter description:

Execution agency. You can optimize performance by configuring a separate agency for function execution, otherwise, the same agency is used for both execution and configuration.

Value range:

None

description

String

Parameter description:

Description of the function.

Value range:

None

last_modified

String

Parameter description:

Time when the function was last updated.

Value range:

UTC time.

func_vpc

FuncVpc object

VPC configuration. An agency with VPC permissions must be configured for the function.

mount_config

MountConfig object

Mounting configuration.

reserved_instance_count

Integer

Parameter description:

The number of instances reserved for a function.

Value range:

None

depend_list

Array of strings

Parameter description:

Dependency IDs.

Value range:

None

depend_version_list

Array of strings

Parameter description:

Dependency versions.

Value range:

None

strategy_config

StrategyConfig object

Parameter description:

Function policy configuration.

status

Integer

Parameter description:

Function status.

Value range:

  • 0: The function is enabled.

  • 1: The function is disabled.

extend_config

String

Parameter description:

Function extension configuration. This field is discarded.

Value range:

None

dependencies

Array of Dependency objects

Parameter description:

Dependency packages.

Value range:

None

initializer_handler

String

Parameter description:

Initializer of the function in the format of "xx.xx". It must contain a period (.). ". This parameter is mandatory when the initialization function is configured.

For example, for the Node.js function myfunction.initializer, the file name is myfunction.js, and the initialization input is

The interface function name is initializer.

Value range:

None

initializer_timeout

Integer

Parameter description:

Initialization timeout interval. The timeout function will be forcibly stopped. This parameter is mandatory when the initialization function is configured.

Value range:

[1, 300]

pre_stop_handler

String

The pre-stop handler of a function. The value must contain a period (.) in the format of xx.xx. For example, for Node.js function myfunction.pre_stop_handler, the file name is myfunction.js, and the initialization function is pre_stop_handler.

pre_stop_timeout

Integer

Parameter description:

Initialization timeout interval. The timeout function will be forcibly stopped.

Value range:

1 to 90 seconds

enterprise_project_id

String

Parameter description:

Enterprise project ID. This parameter is mandatory if you create a function as an enterprise user.

Value range:

None

long_time

Boolean

Parameter description:

Whether to allow a long timeout.

Value range:

  • true: Long-time timeout setting is allowed.

  • false: Long-time timeout setting is not allowed.

log_group_id

String

Parameter description:

Log group ID.

Value range:

None

log_stream_id

String

Parameter description:

Log stream ID.

Value range:

None

type

String

Parameter description:

Function Version

Value range:

  • v2: official version

  • v1: deprecated version.

enable_cloud_debug

String

Parameter description:

Whether to enable cloud debugging in the CloudDebug scenario (deprecated)

Value range:

None

enable_dynamic_memory

Boolean

Parameter description:

Whether to enable dynamic memory allocation.

Value range:

  • true: enabled.

false (disabled)

is_stateful_function

Boolean

Parameter description:

Whether stateful functions are supported. This parameter is supported in FunctionGraph v2.

Value range:

  • true: supported

  • false: disabled.

custom_image

CustomImage object

Parameter description:

Container image.

is_bridge_function

Boolean

Parameter description:

Whether this is a bridge function.

Value range:

  • true: Yes

false: no.

apig_route_enable

Boolean

Parameter description:

Whether to configure gateway routing rules.

Value range:

true: configure

false: not configure

heartbeat_handler

String

Parameter description:

Entry of the heartbeat function. The rule is xx.xx and must contain a period (.). This parameter can be configured only for Java functions.

The heartbeat function entry must be in the same file as your function handler. This parameter is mandatory when the heartbeat function is enabled.

Value range:

None

enable_class_isolation

Boolean

Definition

Whether to enable class isolation. This parameter can be configured only for Java functions. Once enabled, it enables to dump logs to Kafka and improve class loading efficiency. However, this may cause compatibility issues.

Range

  • true: Yes

  • false: No

allow_ephemeral_storage

Boolean

Parameter description:

Indicates whether ephemeral storage can be configured.

Value range:

true: yes

false: not configure

ephemeral_storage

Integer

Parameter description:

Ephemeral storage. By default, the /tmp directory of each function is 512 MB. You can increase the size to 10,240 MB (10 GB) if necessary.

Value range:

  • 512: 512 MB.

  • 10240: 10 GB.

network_controller

NetworkControlConfig object

Definition

Network configuration.

Value range:

None

resource_id

String

Parameter description:

Unique ID of a function resource

Value range:

None

is_return_stream

Boolean

Parameter description:

Whether to return stream data. (discarded)

Value range:

None

enable_auth_in_header

Boolean

Parameter description:

Whether to allow authentication information to be added to the request header. This parameter is supported only by custom image functions.

Value range:

  • true: enabled.

false: An anonymous request is not allowed.

lts_custom_tag

Map<String,String>

Definition

Custom log tag. You can configure tags to report logs to LTS when a function is executed. You can filter function logs by tag.

Range

String mapping pair

enable_lts_log

Boolean

Definition

Whether to enable logging.

Range

  • true: Yes. If this parameter is set to true and log_config is not passed, FunctionGraph automatically creates a log group and log stream.

  • false: No

user_data_encrypt_kms_key_id

String

Definition

ID of the KMS master key used to encrypt environment variables.

Range

[0, 36]

code_encrypt_kms_key_id

String

Definition

ID of the KMS master key used to encrypt user code.

Range

[0, 36]

tags

String

Definition

Function tag.

Range

N/A

Table 14 FuncVpc

Parameter

Type

Description

domain_id

String

Parameter description:

Tenant account ID.

Value range:

None

namespace

String

Parameter description:

Project ID.

Value range:

None

vpc_name

String

Definition:

VPC name

Value range:

None

vpc_id

String

Parameter description:

VPC ID.

Value range:

None

subnet_name

String

Parameter description:

Subnet name.

Value range:

None

subnet_id

String

Parameter description:

Subnet ID.

Value range:

None

cidr

String

Parameter description:

Subnet mask.

Value range:

None

gateway

String

Parameter description:

Gateway.

Value range:

None

security_groups

Array of strings

Parameter description:

Security Group

Value range:

Character string list

is_safety

Boolean

Definition

Whether to enable secure access. When secure access is enabled, you need to configure the VPCEP network to establish a secure VPC connection to private domain names. Once enabled, this feature cannot be disabled.

Range

  • true: Yes

  • false: No

Table 15 MountConfig

Parameter

Type

Description

mount_user

MountUser object

User information.

func_mounts

Array of FuncMount objects

Parameter description:

Mounted resources.

Value range:

None

Table 16 MountUser

Parameter

Type

Description

user_id

Integer

Parameter description:

User ID.

Value range:

An integer ranging from -1 to 65534

user_group_id

Integer

Parameter description:

Group ID

Value range:

An integer ranging from -1 to 65534

Table 17 FuncMount

Parameter

Type

Description

mount_type

String

Definition

Mount type. This parameter is mandatory when func_mounts is not empty.

Range

  • sfs: SFS Capacity-Oriented

  • sfsTurbo: SFS

  • ecs: ECS

mount_resource

String

Parameter description:

ID of the mounted resource (cloud service ID). This parameter is mandatory when func_mounts is not empty.

Value range:

None

mount_share_path

String

Parameter description:

Remote mount path. For example, 192.168.0.12:/data. This parameter is mandatory if mount_type is set to ecs.

Value range:

Shared path opened by the ECS

local_mount_path

String

Parameter description:

Function access path. This parameter is mandatory when func_mounts is not empty.

Value range:

Mount directory in the function container. The directory is generally a two-layer structure.

Table 18 StrategyConfig

Parameter

Type

Description

concurrency

Integer

Parameter description:

Specifies the maximum number of instances for a function. The value -1 indicates that the number of instances is not limited.

Value range:

v1: 0 and -1

v2: [–1, 1000]

concurrent_num

Integer

Parameter description:

Specifies the number of concurrent requests per instance. This parameter is supported in v2.

Value range:

[1, 1000]

Table 19 Dependency

Parameter

Type

Description

id

String

Parameter description:

Dependency version ID.

Value range:

None

owner

String

Parameter description:

Domain ID of the dependency owner.

Value range:

None

link

String

Parameter description:

URL of the dependency on OBS.

Value range:

OBS link

runtime

String

Parameter description:

Runtime of a function.

Value range:

  • Java8: Java 8

  • Java11: Java 11

  • Java17: Java 17

  • Java21: Java 21

  • Python2.7: Python 2.7

  • Python3.6: Python 3.6

  • Python3.9: Python 3.9

  • Python3.10: Python 3.10

  • Python3.12: Python 3.12

  • Go1.x: Go 1.x

  • Node.js6.10: Nodejs 6.10

  • Node.js8.10: Nodejs 8.10

  • Node.js10.16: Nodejs 10.16

  • Node.js12.13: Nodejs 12.13

  • Node.js14.18: Nodejs 14.18

  • Node.js16.17: Nodejs 16.17

  • Node.js18.15: Nodejs 18.15

  • Node.js20.15: Nodejs 20.15

  • C#(.NET Core 2.1): C# 2.1

  • C#(.NET Core 3.1): C# 3.1

  • C#(.NET Core 6.0): C# 6.0

  • C#(.NET Core 8.0): C# 8.0

Custom

  • PHP7.3: Php 7.3

  • PHP8.3: Php 8.3

  • Cangjie1.0

  • Cangjie0.52.3

  • HTTP

Custom image-based functions

etag

String

Parameter description:

MD5 value of a dependency.

Value range:

None

size

Long

Parameter description:

Dependency size.

Value range:

None

name

String

Parameter description:

Name of a dependency package.

Value range:

None

description

String

Parameter description:

Dependency description.

Value range:

None

file_name

String

Parameter description:

File name of a dependency package (ZIP).

Value range:

None

version

Long

Parameter description:

Dependency version ID.

Value range:

None

dep_id

String

Parameter description:

Dependency ID.

Value range:

None

last_modified

String

Parameter description:

Time when the function was last updated.

Value range:

None

Table 20 CustomImage

Parameter

Type

Description

enabled

Boolean

Parameter description:

Whether to use an image. If no image is used, the following parameters do not take effect.

Value range:

true: An image is used.

false: No image is used.

image

String

Parameter description:

Image address.

Value range:

None

command

String

Parameter description:

Command for starting a container image.

Value range:

None

args

String

Parameter description:

Command line parameter for starting a container image.

Value range:

None

working_dir

String

Parameter description:

Working directory of an image container.

Value range:

None

uid

String

Parameter description:

User ID of an image container.

Value range:

None

gid

String

Parameter description:

User group ID of an image container.

Value range:

None

is_public

Boolean

Parameter description:

Whether the image is a public image.

Value range:

None

Table 21 NetworkControlConfig

Parameter

Type

Description

disable_public_network

Boolean

Parameter description:

Disable public access.

Value range:

true: public network access is disabled.

false: public network access is allowed.

trigger_access_vpcs

Array of VpcConfig objects

Parameter description:

VPC access restriction.

Value range:

None

Table 22 VpcConfig

Parameter

Type

Description

vpc_name

String

Parameter description:

VPC name.

Value range:

None

vpc_id

String

VPC ID.

Status code: 400

Table 23 Response body parameters

Parameter

Type

Description

error_code

String

Error code.

error_msg

String

Error message.

Status code: 401

Table 24 Response body parameters

Parameter

Type

Description

error_code

String

Error code.

error_msg

String

Error message.

Status code: 403

Table 25 Response body parameters

Parameter

Type

Description

error_code

String

Error code.

error_msg

String

Error message.

Status code: 404

Table 26 Response body parameters

Parameter

Type

Description

error_code

String

Error code.

error_msg

String

Error message.

Status code: 500

Table 27 Response body parameters

Parameter

Type

Description

error_code

String

Error code.

error_msg

String

Error message.

Status code: 503

Table 28 Response body parameters

Parameter

Type

Description

error_code

String

Error code.

error_msg

String

Error message.

Example Requests

  • Create a Python 2.7 function with 128 MB memory and 3s timeout. Add environment variable password and mount a disk.

    POST https://{Endpoint}/v2/{project_id}/fgs/functions
    
    {
      "func_name" : "xxx",
      "package" : "xxx",
      "runtime" : "Python2.7",
      "handler" : "index.handler",
      "type" : "v2",
      "memory_size" : 128,
      "timeout" : 3,
      "code_type" : "inline",
      "mount_config" : {
        "mount_user" : {
          "user_id" : -1,
          "user_group_id" : -1
        },
        "func_mounts" : [ {
          "mount_resource" : "268xxx-d3xx-4cxx-98xx-d1dbxxx",
          "local_mount_path" : "/mnt",
          "mount_type" : "sfsTurbo"
        } ]
      },
      "encrypted_user_data" : "{\"password\":\"1234\"}",
      "func_code" : {
        "file" : "xxxxx",
        "link" : ""
      }
    }
  • Create a Python 3.9 function with 128 MB memory and 3s timeout, and upload the code from OBS.

    POST https://{Endpoint}/v2/{project_id}/fgs/functions
    
    {
      "func_name" : "xxx",
      "package" : "xxx",
      "runtime" : "Python3.9",
      "handler" : "index.handler",
      "type" : "v2",
      "memory_size" : 128,
      "timeout" : 3,
      "code_type" : "obs",
      "code_url" : "https:xxx"
    }
  • Create a custom image function named xxx. The memory size is 128 MB, the timeout period is 3s, and the code is uploaded by SWR.

    POST https://{Endpoint}/v2/{project_id}/fgs/functions
    
    {
      "func_name" : "xxx",
      "package" : "xxx",
      "runtime" : "Custom Image",
      "handler" : "-",
      "type" : "v2",
      "memory_size" : 128,
      "timeout" : 3,
      "code_type" : "obs",
      "code_url" : "https:xxx",
      "xrole" : "xxx",
      "custom_image" : {
        "enabled" : true,
        "image" : "swr.xxx"
      }
    }

Example Responses

Status code: 200

{
  "func_urn" : "urn:fss:xxxxxxxxx:c3b2459a6d5e4b548e6777e57852692d:function:default:TestCreateFunctionInPythonSdk:latest",
  "func_name" : "TestCreateFunctionInPythonSdk",
  "domain_id" : "14ee2e3501124efcbca7998baa24xxxx",
  "namespace" : "46b6f338fc3445b8846c71dfb1fbxxxx",
  "project_name" : "xxxxxxxxxx",
  "package" : "default",
  "runtime" : "Python3.6",
  "timeout" : 3,
  "handler" : "index.handler",
  "memory_size" : 128,
  "encrypted_user_data" : "{\"password\":\"\"}",
  "mount_config" : {
    "mount_user" : {
      "user_id" : -1,
      "user_group_id" : -1
    },
    "func_mounts" : [ {
      "mount_resource" : "268xxx-d3xx-4cxx-98xx-d1dbxxx",
      "local_mount_path" : "/mnt",
      "mount_type" : "sfsTurbo"
    } ]
  },
  "cpu" : 1024,
  "code_type" : "inline",
  "code_filename" : "index.py",
  "code_size" : 100,
  "digest" : "1c8610d1870731a818a037f1d2adf3223e8ac351aeb293fb1f8eabd2e9820069a61ed8b5d38182e760adc33a307d0e957afc357f415cd8c9c3ff6f0426fd85cd",
  "version" : "latest",
  "image_name" : "latest-191025153727@zehht",
  "last_modified" : "2019-10-25 15:37:27",
  "status" : 0,
  "strategy_config" : {
    "concurrency" : 0
  }
}

Status code: 400

{
  "error_code" : "FSS.0401",
  "error_msg" : "not permit"
}

Status code: 401

{
  "error_code" : "FSS.0401",
  "error_msg" : "not permit"
}

Status code: 403

{
  "error_code" : "FSS.0401",
  "error_msg" : "not permit"
}

SDK Sample Code

The SDK sample code is as follows.

Java

  • Create a Python 2.7 function with 128 MB memory and 3s timeout. Add environment variable password and mount a disk.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.functiongraph.v2.region.FunctionGraphRegion;
    import com.huaweicloud.sdk.functiongraph.v2.*;
    import com.huaweicloud.sdk.functiongraph.v2.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    
    public class CreateFunctionSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
            String projectId = "{project_id}";
    
            ICredential auth = new BasicCredentials()
                    .withProjectId(projectId)
                    .withAk(ak)
                    .withSk(sk);
    
            FunctionGraphClient client = FunctionGraphClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(FunctionGraphRegion.valueOf("<YOUR REGION>"))
                    .build();
            CreateFunctionRequest request = new CreateFunctionRequest();
            CreateFunctionRequestBody body = new CreateFunctionRequestBody();
            List<FuncMount> listMountConfigFuncMounts = new ArrayList<>();
            listMountConfigFuncMounts.add(
                new FuncMount()
                    .withMountType("sfsTurbo")
                    .withMountResource("268xxx-d3xx-4cxx-98xx-d1dbxxx")
                    .withLocalMountPath("/mnt")
            );
            MountUser mountUserMountConfig = new MountUser();
            mountUserMountConfig.withUserId(-1)
                .withUserGroupId(-1);
            MountConfig mountConfigbody = new MountConfig();
            mountConfigbody.withMountUser(mountUserMountConfig)
                .withFuncMounts(listMountConfigFuncMounts);
            FuncCode funcCodebody = new FuncCode();
            funcCodebody.withFile("xxxxx")
                .withLink("");
            body.withType(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("v2"));
            body.withMountConfig(mountConfigbody);
            body.withFuncCode(funcCodebody);
            body.withEncryptedUserData("{"password":"1234"}");
            body.withCodeType(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("inline"));
            body.withMemorySize(128);
            body.withHandler("index.handler");
            body.withTimeout(3);
            body.withRuntime(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("Python2.7"));
            body.withPackage("xxx");
            body.withFuncName("xxx");
            request.withBody(body);
            try {
                CreateFunctionResponse response = client.createFunction(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • Create a Python 3.9 function with 128 MB memory and 3s timeout, and upload the code from OBS.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.functiongraph.v2.region.FunctionGraphRegion;
    import com.huaweicloud.sdk.functiongraph.v2.*;
    import com.huaweicloud.sdk.functiongraph.v2.model.*;
    
    
    public class CreateFunctionSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
            String projectId = "{project_id}";
    
            ICredential auth = new BasicCredentials()
                    .withProjectId(projectId)
                    .withAk(ak)
                    .withSk(sk);
    
            FunctionGraphClient client = FunctionGraphClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(FunctionGraphRegion.valueOf("<YOUR REGION>"))
                    .build();
            CreateFunctionRequest request = new CreateFunctionRequest();
            CreateFunctionRequestBody body = new CreateFunctionRequestBody();
            body.withType(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("v2"));
            body.withCodeUrl("https:xxx");
            body.withCodeType(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("obs"));
            body.withMemorySize(128);
            body.withHandler("index.handler");
            body.withTimeout(3);
            body.withRuntime(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("Python3.9"));
            body.withPackage("xxx");
            body.withFuncName("xxx");
            request.withBody(body);
            try {
                CreateFunctionResponse response = client.createFunction(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • Create a custom image function named xxx. The memory size is 128 MB, the timeout period is 3s, and the code is uploaded by SWR.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.functiongraph.v2.region.FunctionGraphRegion;
    import com.huaweicloud.sdk.functiongraph.v2.*;
    import com.huaweicloud.sdk.functiongraph.v2.model.*;
    
    
    public class CreateFunctionSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
            String projectId = "{project_id}";
    
            ICredential auth = new BasicCredentials()
                    .withProjectId(projectId)
                    .withAk(ak)
                    .withSk(sk);
    
            FunctionGraphClient client = FunctionGraphClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(FunctionGraphRegion.valueOf("<YOUR REGION>"))
                    .build();
            CreateFunctionRequest request = new CreateFunctionRequest();
            CreateFunctionRequestBody body = new CreateFunctionRequestBody();
            CustomImage customImagebody = new CustomImage();
            customImagebody.withEnabled(true)
                .withImage("swr.xxx");
            body.withType(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("v2"));
            body.withXrole("xxx");
            body.withCustomImage(customImagebody);
            body.withCodeUrl("https:xxx");
            body.withCodeType(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("obs"));
            body.withMemorySize(128);
            body.withHandler("-");
            body.withTimeout(3);
            body.withRuntime(CreateFunctionRequestBody.CreateFunctionRequestBody.fromValue("Custom Image"));
            body.withPackage("xxx");
            body.withFuncName("xxx");
            request.withBody(body);
            try {
                CreateFunctionResponse response = client.createFunction(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    

Python

  • Create a Python 2.7 function with 128 MB memory and 3s timeout. Add environment variable password and mount a disk.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    # coding: utf-8
    
    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkfunctiongraph.v2.region.functiongraph_region import FunctionGraphRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkfunctiongraph.v2 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = os.environ["CLOUD_SDK_AK"]
        sk = os.environ["CLOUD_SDK_SK"]
        projectId = "{project_id}"
    
        credentials = BasicCredentials(ak, sk, projectId)
    
        client = FunctionGraphClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(FunctionGraphRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = CreateFunctionRequest()
            listFuncMountsMountConfig = [
                FuncMount(
                    mount_type="sfsTurbo",
                    mount_resource="268xxx-d3xx-4cxx-98xx-d1dbxxx",
                    local_mount_path="/mnt"
                )
            ]
            mountUserMountConfig = MountUser(
                user_id=-1,
                user_group_id=-1
            )
            mountConfigbody = MountConfig(
                mount_user=mountUserMountConfig,
                func_mounts=listFuncMountsMountConfig
            )
            funcCodebody = FuncCode(
                file="xxxxx",
                link=""
            )
            request.body = CreateFunctionRequestBody(
                type="v2",
                mount_config=mountConfigbody,
                func_code=funcCodebody,
                encrypted_user_data="{"password":"1234"}",
                code_type="inline",
                memory_size=128,
                handler="index.handler",
                timeout=3,
                runtime="Python2.7",
                package="xxx",
                func_name="xxx"
            )
            response = client.create_function(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • Create a Python 3.9 function with 128 MB memory and 3s timeout, and upload the code from OBS.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    # coding: utf-8
    
    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkfunctiongraph.v2.region.functiongraph_region import FunctionGraphRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkfunctiongraph.v2 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = os.environ["CLOUD_SDK_AK"]
        sk = os.environ["CLOUD_SDK_SK"]
        projectId = "{project_id}"
    
        credentials = BasicCredentials(ak, sk, projectId)
    
        client = FunctionGraphClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(FunctionGraphRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = CreateFunctionRequest()
            request.body = CreateFunctionRequestBody(
                type="v2",
                code_url="https:xxx",
                code_type="obs",
                memory_size=128,
                handler="index.handler",
                timeout=3,
                runtime="Python3.9",
                package="xxx",
                func_name="xxx"
            )
            response = client.create_function(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • Create a custom image function named xxx. The memory size is 128 MB, the timeout period is 3s, and the code is uploaded by SWR.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    # coding: utf-8
    
    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkfunctiongraph.v2.region.functiongraph_region import FunctionGraphRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkfunctiongraph.v2 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = os.environ["CLOUD_SDK_AK"]
        sk = os.environ["CLOUD_SDK_SK"]
        projectId = "{project_id}"
    
        credentials = BasicCredentials(ak, sk, projectId)
    
        client = FunctionGraphClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(FunctionGraphRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = CreateFunctionRequest()
            customImagebody = CustomImage(
                enabled=True,
                image="swr.xxx"
            )
            request.body = CreateFunctionRequestBody(
                type="v2",
                xrole="xxx",
                custom_image=customImagebody,
                code_url="https:xxx",
                code_type="obs",
                memory_size=128,
                handler="-",
                timeout=3,
                runtime="Custom Image",
                package="xxx",
                func_name="xxx"
            )
            response = client.create_function(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    

Go

  • Create a Python 2.7 function with 128 MB memory and 3s timeout. Add environment variable password and mount a disk.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        functiongraph "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
        projectId := "{project_id}"
    
        auth, err := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithProjectId(projectId).
            SafeBuild()
    
        if err != nil {
            fmt.Println(err)
            return
        }
    
        hcClient, err := functiongraph.FunctionGraphClientBuilder().
             WithRegion(region.ValueOf("<YOUR REGION>")).
             WithCredential(auth).
             SafeBuild()
    
    
        if err != nil {
            fmt.Println(err)
            return
        }
    
        client := functiongraph.NewFunctionGraphClient(hcClient)
    
        request := &model.CreateFunctionRequest{}
    	var listFuncMountsMountConfig = []model.FuncMount{
            {
                MountType: "sfsTurbo",
                MountResource: "268xxx-d3xx-4cxx-98xx-d1dbxxx",
                LocalMountPath: "/mnt",
            },
        }
    	mountUserMountConfig := &model.MountUser{
    		UserId: int32(-1),
    		UserGroupId: int32(-1),
    	}
    	mountConfigbody := &model.MountConfig{
    		MountUser: mountUserMountConfig,
    		FuncMounts: listFuncMountsMountConfig,
    	}
    	fileFuncCode:= "xxxxx"
    	linkFuncCode:= ""
    	funcCodebody := &model.FuncCode{
    		File: &fileFuncCode,
    		Link: &linkFuncCode,
    	}
    	typeCreateFunctionRequestBody:= model.GetCreateFunctionRequestBodyTypeEnum().V2
    	encryptedUserDataCreateFunctionRequestBody:= "{"password":"1234"}"
    	codeTypeCreateFunctionRequestBody:= model.GetCreateFunctionRequestBodyCodeTypeEnum().INLINE
    	request.Body = &model.CreateFunctionRequestBody{
    		Type: &typeCreateFunctionRequestBody,
    		MountConfig: mountConfigbody,
    		FuncCode: funcCodebody,
    		EncryptedUserData: &encryptedUserDataCreateFunctionRequestBody,
    		CodeType: &codeTypeCreateFunctionRequestBody,
    		MemorySize: int32(128),
    		Handler: "index.handler",
    		Timeout: int32(3),
    		Runtime: model.GetCreateFunctionRequestBodyRuntimeEnum().PYTHON2_7,
    		Package: "xxx",
    		FuncName: "xxx",
    	}
    	response, err := client.CreateFunction(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • Create a Python 3.9 function with 128 MB memory and 3s timeout, and upload the code from OBS.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        functiongraph "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
        projectId := "{project_id}"
    
        auth, err := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithProjectId(projectId).
            SafeBuild()
    
        if err != nil {
            fmt.Println(err)
            return
        }
    
        hcClient, err := functiongraph.FunctionGraphClientBuilder().
             WithRegion(region.ValueOf("<YOUR REGION>")).
             WithCredential(auth).
             SafeBuild()
    
    
        if err != nil {
            fmt.Println(err)
            return
        }
    
        client := functiongraph.NewFunctionGraphClient(hcClient)
    
        request := &model.CreateFunctionRequest{}
    	typeCreateFunctionRequestBody:= model.GetCreateFunctionRequestBodyTypeEnum().V2
    	codeUrlCreateFunctionRequestBody:= "https:xxx"
    	codeTypeCreateFunctionRequestBody:= model.GetCreateFunctionRequestBodyCodeTypeEnum().OBS
    	request.Body = &model.CreateFunctionRequestBody{
    		Type: &typeCreateFunctionRequestBody,
    		CodeUrl: &codeUrlCreateFunctionRequestBody,
    		CodeType: &codeTypeCreateFunctionRequestBody,
    		MemorySize: int32(128),
    		Handler: "index.handler",
    		Timeout: int32(3),
    		Runtime: model.GetCreateFunctionRequestBodyRuntimeEnum().PYTHON3_9,
    		Package: "xxx",
    		FuncName: "xxx",
    	}
    	response, err := client.CreateFunction(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • Create a custom image function named xxx. The memory size is 128 MB, the timeout period is 3s, and the code is uploaded by SWR.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        functiongraph "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/functiongraph/v2/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
        projectId := "{project_id}"
    
        auth, err := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            WithProjectId(projectId).
            SafeBuild()
    
        if err != nil {
            fmt.Println(err)
            return
        }
    
        hcClient, err := functiongraph.FunctionGraphClientBuilder().
             WithRegion(region.ValueOf("<YOUR REGION>")).
             WithCredential(auth).
             SafeBuild()
    
    
        if err != nil {
            fmt.Println(err)
            return
        }
    
        client := functiongraph.NewFunctionGraphClient(hcClient)
    
        request := &model.CreateFunctionRequest{}
    	enabledCustomImage:= true
    	imageCustomImage:= "swr.xxx"
    	customImagebody := &model.CustomImage{
    		Enabled: &enabledCustomImage,
    		Image: &imageCustomImage,
    	}
    	typeCreateFunctionRequestBody:= model.GetCreateFunctionRequestBodyTypeEnum().V2
    	xroleCreateFunctionRequestBody:= "xxx"
    	codeUrlCreateFunctionRequestBody:= "https:xxx"
    	codeTypeCreateFunctionRequestBody:= model.GetCreateFunctionRequestBodyCodeTypeEnum().OBS
    	request.Body = &model.CreateFunctionRequestBody{
    		Type: &typeCreateFunctionRequestBody,
    		Xrole: &xroleCreateFunctionRequestBody,
    		CustomImage: customImagebody,
    		CodeUrl: &codeUrlCreateFunctionRequestBody,
    		CodeType: &codeTypeCreateFunctionRequestBody,
    		MemorySize: int32(128),
    		Handler: "-",
    		Timeout: int32(3),
    		Runtime: model.GetCreateFunctionRequestBodyRuntimeEnum().CUSTOM_IMAGE,
    		Package: "xxx",
    		FuncName: "xxx",
    	}
    	response, err := client.CreateFunction(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    

More

For SDK sample code of more programming languages, see the Sample Code tab in API Explorer. SDK sample code can be automatically generated.

Status Codes

Status Code

Description

200

ok

400

Bad request.

401

Unauthorized.

403

Forbidden.

404

Not found.

500

Internal server error.

503

Service unavailable.

Error Codes

See Error Codes.