Skip to content

Open API and SDK

New in version 2.6.4

DataFlux Func provides complete Open API support, which can be invoked programmatically using the companion DataFlux Func SDK.

When you need to run scripts directly in a local Python environment, you can use the local script engine without creating an Access Key or connecting to the DataFlux Func service.

1. Enable the Open API Documentation Page

In the "Experimental Features" section, you can enable the Open API documentation page.

The DataFlux Func SDK includes signing capability and is distributed as a single file. Users can directly add it to their project for use.

enable-openapi-doc.png

2. Create an Access Key

  1. Log in to your DataFlux Func
  2. Enable Access Key management in "Admin / Experimental Features"
  3. In "Admin / Access Key", click "New" to create an Access Key

3. Use the SDK to Send Requests

The DataFlux Func SDK supports multiple programming languages. The download URLs are as follows:

Language Download URL Description
Python dataflux_func_sdk.py Single file; basic usage has no dependencies. The upload feature depends on the requests library
Node.js dataflux_func_sdk.js Single file; basic usage has no dependencies. The upload feature depends on the form-data library
Golang dataflux_func_sdk.go Single file, completely dependency-free
Demo: dataflux_func_sdk_demo.go

An example of sending requests is as follows:

Python
 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
from dataflux_func_sdk import DataFluxFunc

# Create a DataFlux Func operation object
dff = DataFluxFunc(ak_id='ak-xxxxx', ak_secret='xxxxxxxxxx', host='localhost:8088')

# Enable Debug
dff.debug = True

# Send GET request
try:
    status_code, resp = dff.get('/api/v1/do/ping')

except Exception as e:
    print(e)
    raise

# Send POST request
try:
    body = {
        'echo': {
            'int'    : 1,
            'str'    : 'Hello World',
            'none'   : None,
            'boolean': True,
        }
    }
    status_code, resp = dff.post('/api/v1/do/echo', body=body)

except Exception as e:
    print(e)
    raise

# Upload file
try:
    filename = 'your_file'
    with open(filename, 'rb') as _f:
        file_buffer = _f.read()

    fields = {
        'folder': 'test'
    }

    status_code, resp = dff.upload('/api/v1/resources/do/upload',
        file_buffer=file_buffer,
        filename=filename,
        fields=fields)

except Exception as e:
    print(e)
    raise
JavaScript
 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
var fs = require('fs');
var DataFluxFunc = require('./dataflux_func_sdk.js').DataFluxFunc;

// Create a DataFlux Func operation object
var opt = {
  akId    : 'ak-xxxxx',
  akSecret: 'xxxxxxxxxx',
  host    : 'localhost:8088',
};
var dff = new DataFluxFunc(opt);

// Enable Debug
dff.debug = true;

// Send GET request
var getOpt = {
  path: '/api/v1/do/ping',
};
dff.get(getOpt, function(err, respData, respStatusCode) {
  if (err) {
    console.error(err);
    return;
  }

  // Send POST request
  var postOpt = {
    path: '/api/v1/do/echo',
    body: {
      'echo': {
        'int'    : 1,
        'str'    : 'Hello World',
        'none'   : null,
        'boolean': true,
      }
    }
  };
  dff.post(postOpt, function(err, respData, respStatusCode) {
    if (err) {
      console.error(err);
      return;
    }

    // Upload file
    var filename = 'your_file';
    var uploadOpt = {
      path      : '/api/v1/resources/do/upload',
      fileBuffer: fs.readFileSync(filename),
      filename  : filename,
      fields    : {
        'folder': 'test'
      },
    };
    dff.upload(uploadOpt, function(err, respData, respStatusCode) {
      if (err) {
        console.error(err);
        return;
      }
    });
  });
});
Go
 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
package main

import (
    "os"
    "bytes"
    "fmt"
    "io"
    "mime/multipart"

    // DataFlux Func SDK
    "./dataflux_func_sdk"
)

var (
    colorMap = map[interface{}]string{
        "grey":    "\033[0;30m",
        "red":     "\033[0;31m",
        "green":   "\033[0;32m",
        "yellow":  "\033[0;33m",
        "blue":    "\033[0;34m",
        "magenta": "\033[0;35m",
        "cyan":    "\033[0;36m",
    }
)

func main() {
    host := "localhost:8088"
    if len(os.Args) >= 2 {
        host = os.Args[1]
    }

    // Create a DataFlux Func operation object
    dff := dataflux_func_sdk.NewDataFluxFunc("ak-xxxxx", "xxxxxxxxxx", host, 30, false)

    // Enable Debug
    dff.Debug = true

    // Send GET request
    _, _, err := dff.Get("/api/v1/do/ping", nil, nil, "")
    if err != nil {
        panic(err)
    }

    // Send POST request
    body := map[string]interface{}{
        "echo": map[string]interface{}{
            "int"    : 1,
            "str"    : "Hello World",
            "none"   : nil,
            "boolean": true,
        },
    }
    _, _, err = dff.Post("/api/v1/do/echo", body, nil, nil, "")
    if err != nil {
        panic(err)
    }

    // Upload file
    filename := "dataflux_func_sdk_demo.go"
    file, _ := os.Open(filename)
    fileContents, _ := io.ReadAll(file)

    uploadBody := &bytes.Buffer{}
    writer := multipart.NewWriter(uploadBody)

    part, _ := writer.CreateFormFile("files", filename)
    part.Write(fileContents)

    fields := map[string]string{
        "folder": "test",
    }
    for key, value := range fields {
        writer.WriteField(key, fmt.Sprintf("%v", value))
    }

    writer.Close()
    contentType := writer.FormDataContentType()

    _, _, err = dff.Upload("/api/v1/resources/do/upload", filename, "", fields, nil, nil, uploadBody, contentType)
    if err != nil {
        panic(err)
    }
}

4. Running Scripts Locally

New in version 8.1.15

Obtain sdk/dataflux_func_local.py from the source code of DataFlux Func 8.1.15 or later, and place it in your local Python project for use. The local engine is a single-file tool that depends only on the Python standard library, requires Python 3.8 or higher, and can run independently of the HTTP SDK, Server, Worker, database, and Redis.

Third-party Python packages used by the scripts themselves must be installed in the same Python environment; the engine does not automatically install dependencies.

4.1 Executing Functions

Place the engine and the script in the same directory, for example:

Text Only
1
2
3
my-scripts/
  dataflux_func_local.py
  demo__example.py

The content of demo__example.py is as follows:

Python
1
2
3
@DFF.API('Calculate the sum of two numbers')
def plus(x, y):
    return x + y

Execute in that directory:

Bash
1
python dataflux_func_local.py run demo__example.plus --kwargs '{"x": 1, "y": 2}'

The standard output is 3. --kwargs must be a JSON object; when omitted, {} is used. You can also call ordinary functions that are not decorated with @DFF.API.

4.2 Script Directory and Imports

The script root directory defaults to the current working directory when the command is started, and can be specified with --root:

Bash
1
python dataflux_func_local.py run demo__example.plus --root ./exported --kwargs '{"x": 1, "y": 2}'

For demo__example.plus, the following script paths relative to the root directory are supported:

Text Only
1
2
3
4
demo__example.py
demo__example.draft.py
script-sets/demo/example.py
script-sets/demo/demo__example.py

--root can also point directly to the script-sets directory. Only one matching file is kept for each script ID; ambiguity is reported when multiple matching files are found. The engine reads local file contents and does not distinguish between draft and published versions.

Scripts can import scripts from the same script set using import __helper, and can import scripts from other script sets using import other__helper. During execution, each imported script is loaded only once and its module is reused. Required scripts should all be placed within the specified root directory; the engine does not parse META.yaml and will not automatically download missing scripts or resources.

4.3 Supported Script Capabilities

Feature Local Behavior
DFF.API Records function metadata and common decorator parameters; the specified function is explicitly invoked by the command
print, DFF.LOG, DFF.VAR Logs are written to standard error; output from Python, native libraries, and subprocesses that inherit standard output is also redirected to standard error
DFF.ENV Reads strings from the process environment; supports direct calls and get, keys, ref; does not provide platform environment variable types or automatic password masking
DFF.CTX Saves the context of the current run; when reading, a snapshot is copied via JSON; saved values should be JSON-compatible
DFF.RSRC Resolves resource relative paths to <root>/resources for Python file operations; paths cannot go outside that directory
DFF.TEMP_DIR Creates a temporary directory on first use; can be cleared manually; automatically cleaned up after execution ends or when an exception is thrown
DFF.RESP Outputs a JSON object containing returnValue and responseControl without starting an HTTP service

Local execution uses debug mode, where _DFF_IS_DEBUG and _DFF_DEBUG are True, and _DFF_IS_PUBLISH is False; HTTP request and Cron Job contexts are empty.

Parameters in DFF.API such as timeout, cache, queue, Cron Job, HTTP API, authentication, and auto-run are retained only as declarations and do not trigger corresponding platform behaviors; when the entry function declares these parameters, the engine outputs a warning to standard error. In particular, the engine does not terminate the function when the declared timeout is reached.

Custom function metadata can use custom or custom_json; custom_yaml is not supported. Unlisted capabilities such as Connector, persistent storage, simple cache, thread pool, and platform management are also not supported, and accessing them will raise a clear error.

4.4 Results and Errors

On successful execution, standard output contains a JSON result; the function return value must be serializable to JSON, and NaN and Infinity are rejected. Logs and errors are written to standard error, so the result can be saved separately:

Bash
1
python dataflux_func_local.py run demo__example.plus --kwargs '{"x": 1, "y": 2}' > result.json

Argument errors (including invalid --kwargs) exit with code 2; Script, import, or result serialization errors exit with code 1, with the exception stack pointing to the local source file; user interruption exits with code 130.