Process data with a Python script: full text
This page has every step and detail. The overview is the short version.
Build an API that runs a Python script to validate and convert data formats (JSON, YAML). It shows the python component: how it receives request data, and how its printed output becomes the resource result.
The python component runs a script and returns its stdout as the resource's output. If the script prints a JSON object, later resources can read its fields. Before the script runs, kdeps puts the values of expression placeholders into the script text. For this reason, put them in triple quotes to keep the script valid Python.
Step 1: create the project
bash
mkdir data-tools
cd data-tools
mkdir resourcesStep 2: define the route
Create workflow.yaml:
yaml
# workflow.yaml
apiVersion: kdeps.io/v1
kind: Workflow
metadata:
name: data-tools
version: "1.0.0"
targetActionId: process
deploy:
apiServer:
portNum: 16396
routes:
- path: /format
methods: [POST]
runtime:
pythonVersion: "3.12"Step 3: the python component call
Create resources/process.yaml:
yaml
# resources/process.yaml
actionId: process
name: Format operations
validations:
methods: [POST]
routes: [/format]
component:
name: python
with:
packages:
- pyyaml # installed into the script's environment
script: |
import json, sys
data = """{{ input('data') }}"""
fmt = "{{ input('format', 'json') }}".lower()
operation = "{{ input('operation', 'validate') }}".lower()
def run():
if operation == "validate":
if fmt == "json":
json.loads(data)
elif fmt == "yaml":
import yaml; yaml.safe_load(data)
else:
return {"error": f"unsupported format: {fmt}"}
return {"valid": True}
if operation == "convert": # json -> yaml
import yaml
return {"output": yaml.dump(json.loads(data), default_flow_style=False).rstrip()}
return {"error": f"unknown operation: {operation}"}
try:
result = run()
except Exception as exc:
result = {"valid": False, "error": str(exc)}
print(json.dumps(result)) # stdout becomes the resource output
apiResponse:
success: true
response:
result: "{{ output('process') }}"Step 4: validate and run
bash
kdeps validate .
export KDEPS_API_AUTH_TOKEN=dev-token
kdeps run .Validate a JSON string:
bash
curl -X POST http://localhost:16396/format \
-H "Authorization: Bearer $KDEPS_API_AUTH_TOKEN" \
-H "Content-Type: application/json" \
-d '{"data": "{\"a\": 1}", "format": "json", "operation": "validate"}'Convert JSON to YAML:
bash
curl -X POST http://localhost:16396/format \
-H "Authorization: Bearer $KDEPS_API_AUTH_TOKEN" \
-H "Content-Type: application/json" \
-d '{"data": "{\"a\": 1, \"b\": [2, 3]}", "operation": "convert"}'Response:
json
{ "success": true, "data": { "result": { "output": "a: 1\nb:\n- 2\n- 3" } } }Next steps
- python component - script files, packages, virtualenvs
- Inline resources tutorial -
component:inafter: - Function calling tutorial - a Python script as an LLM tool
- exec component - plain shell commands
