Use AWS jsii to cross language invoker

You can generate Python, Java, and .NET software libraries from a TypeScript source use jsii of AWS Cloud Development Kit (AWS CDK).

Initialization the project constructure

1pnpm init -y
2pnpm install --development jsii jsii-pacmak

The package.json like following this

 1{
 2  "name": "jsii-demo",
 3  "version": "1.0.0",
 4  "description": "A demonstration jsii library",
 5  "main": "index.js",
 6  "scripts": {
 7    "build": "jsii",
 8    "build:watch": "jsii --watch",
 9    "package": "jsii-pacmak"
10  },
11  "keywords": [],
12  "author": {
13    "name": "John Doe",
14    "email": "john.doe@acme.com"
15  },
16  "repository": {
17    "url": "https://github.com/acme/project-name.git"
18  },
19  "license": "ISC",
20  "stability": "stable",
21  "types": "index.d.ts",
22  "jsii": {
23    "outdir": "dist",
24    "versionFormat": "full",
25    "targets": {
26      "java": {
27        "package": "software.aws.jsiisamples.jsii",
28        "maven": {
29          "groupId": "software.aws.jsiisamples.jsii",
30          "artifactId": "jsii-code-samples"
31        }
32      },
33      "python": {
34        "distName": "aws-jsiisamples.jsii-code-samples",
35        "module": "aws_jsiisamples.jsii_code_samples"
36      },
37      "dotnet": {
38        "namespace": "AWSSamples.Jsii",
39        "packageId": "AWSSamples.Jsii",
40        "iconUrl": "https://raw.githubusercontent.com/aws/jsii/master/logo/png/128x128.png"
41      },
42      "go": {
43        "moduleName": "github.com/foo/bar",
44        "packageName": "hello",
45        "versionSuffix": "-devprefix"
46      }
47    }
48  },
49  "devDependencies": {
50    "jsii": "^5.3.7",
51    "jsii-pacmak": "^1.94.0"
52  }
53}

Write the HelloWorld typescript code to index.ts

 1export class HelloWorld {
 2    public sayHello(name: string) {
 3        return `Hello, ${name}`;
 4    }
 5
 6    public fibonacci(num: number) {
 7        let array = [0, 1];
 8        for (let i = 2; i < num + 1; i++) {
 9            array.push(array[i - 2] + array[i - 1]);
10        }
11        return array[num];
12    }
13}

The execute build

1pnpm run build
2# then package to dist folder
3pnpm run package
4# copy the python whl file to other project and install it
5pip install aws_jsiisamples.jsii_code_samples-1.0.0-py3-none-any.whl --force-reinstall

Invoker the javascript code in python

1from aws_jsiisamples.jsii_code_samples import HelloWorld
2
3
4
5if __name__ == "__main__":
6    g = HelloWorld()
7    print(g.say_hello('Tom'))

Reference