ibmrpa-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ibmrpa_sdk/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ from .client import IbmRpaClient
2
+ from .async_client import AsyncIbmRpaClient
3
+ from .config import Settings
4
+ from .exceptions import IbmRpaError
5
+
6
+ __all__ = ["IbmRpaClient", "AsyncIbmRpaClient", "Settings", "IbmRpaError"]
@@ -0,0 +1,132 @@
1
+ import httpx
2
+ from typing import Optional, Any, Dict, Union
3
+ import logging
4
+
5
+ from .config import Settings
6
+ from .auth import AuthStrategy, BearerTokenAuth, ApiKeyAuth, NoAuth
7
+ from .exceptions import (
8
+ IbmRpaHttpError,
9
+ IbmRpaTimeoutError,
10
+ IbmRpaConnectionError,
11
+ IbmRpaRateLimitError,
12
+ IbmRpaError
13
+ )
14
+ from .utils.retry import create_retry_decorator
15
+ from .utils.logging import get_logger
16
+
17
+ logger = get_logger("ibmrpa_sdk.async_client")
18
+
19
+ class AsyncIbmRpaClient:
20
+ def __init__(
21
+ self,
22
+ base_url: Optional[str] = None,
23
+ token: Optional[str] = None,
24
+ settings: Optional[Settings] = None,
25
+ http_client: Optional[httpx.AsyncClient] = None
26
+ ):
27
+ self.settings = settings or Settings()
28
+
29
+ # Override settings if explicitly provided
30
+ if base_url:
31
+ self.settings.base_url = base_url
32
+ if token:
33
+ self.settings.token = token
34
+
35
+ self.settings.validate_setup()
36
+
37
+ # Determine Auth Strategy
38
+ self.auth: AuthStrategy = NoAuth()
39
+ if self.settings.token:
40
+ self.auth = BearerTokenAuth(self.settings.token)
41
+ elif self.settings.api_key:
42
+ self.auth = ApiKeyAuth(self.settings.api_key)
43
+
44
+ # HTTP Client Setup
45
+ self._http = http_client or httpx.AsyncClient(
46
+ base_url=self.settings.base_url,
47
+ timeout=self.settings.timeout,
48
+ verify=self.settings.verify_ssl,
49
+ )
50
+
51
+ # Retry Decorator
52
+ self._retry = create_retry_decorator(
53
+ self.settings.retry_max_attempts,
54
+ self.settings.retry_backoff
55
+ )
56
+
57
+ # Initialize Endpoint Categories
58
+ from .endpoints.authentication import Authentication
59
+ from .endpoints.bots import Bots
60
+ from .endpoints.projects import Projects
61
+ from .endpoints.tenant_management import TenantManagement
62
+ from .endpoints.workspace import Workspace
63
+ from .endpoints.process_management import ProcessManagement
64
+
65
+ self.authentication = Authentication(self)
66
+ self.bots = Bots(self)
67
+ self.projects = Projects(self)
68
+ self.tenant = TenantManagement(self)
69
+ self.workspace = Workspace(self)
70
+ self.process = ProcessManagement(self)
71
+
72
+ async def request(
73
+ self,
74
+ method: str,
75
+ path: str,
76
+ **kwargs
77
+ ) -> httpx.Response:
78
+
79
+ @self._retry
80
+ async def _do_request():
81
+ # Inject Auth
82
+ request = self._http.build_request(method, path, **kwargs)
83
+ request = self.auth.configure(request)
84
+
85
+ try:
86
+ logger.debug(f"Request: {method} {request.url}")
87
+ response = await self._http.send(request)
88
+
89
+ # Handling Errors
90
+ if response.is_error:
91
+ self._handle_error(response)
92
+
93
+ return response
94
+
95
+ except httpx.TimeoutException as e:
96
+ logger.error(f"Timeout: {e}")
97
+ raise IbmRpaTimeoutError(f"Request timed out: {e}") from e
98
+ except httpx.NetworkError as e:
99
+ logger.error(f"Network error: {e}")
100
+ raise IbmRpaConnectionError(f"Network happened: {e}") from e
101
+ except IbmRpaError:
102
+ raise
103
+ except Exception as e:
104
+ logger.error(f"Unexpected error: {e}")
105
+ raise IbmRpaError(f"Unexpected error: {e}") from e
106
+
107
+ return await _do_request()
108
+
109
+ def _handle_error(self, response: httpx.Response):
110
+ status = response.status_code
111
+ try:
112
+ body = response.json()
113
+ except Exception:
114
+ body = response.text
115
+
116
+ logger.error(f"HTTP Error {status}: {body}")
117
+
118
+ if status == 429:
119
+ raise IbmRpaRateLimitError(status, "Too Many Requests", body)
120
+ elif 400 <= status < 500:
121
+ raise IbmRpaHttpError(status, "Client Error", body)
122
+ elif 500 <= status < 600:
123
+ raise IbmRpaHttpError(status, "Server Error", body)
124
+
125
+ async def close(self):
126
+ await self._http.aclose()
127
+
128
+ async def __aenter__(self):
129
+ return self
130
+
131
+ async def __aexit__(self, exc_type, exc_value, traceback):
132
+ await self.close()
ibmrpa_sdk/auth.py ADDED
@@ -0,0 +1,27 @@
1
+ from typing import Any, Protocol, Union
2
+ import httpx
3
+
4
+ class AuthStrategy(Protocol):
5
+ def configure(self, request: httpx.Request) -> httpx.Request:
6
+ ...
7
+
8
+ class BearerTokenAuth:
9
+ def __init__(self, token: str):
10
+ self.token = token
11
+
12
+ def configure(self, request: httpx.Request) -> httpx.Request:
13
+ request.headers["Authorization"] = f"Bearer {self.token}"
14
+ return request
15
+
16
+ class ApiKeyAuth:
17
+ def __init__(self, api_key: str, header_name: str = "x-api-key"):
18
+ self.api_key = api_key
19
+ self.header_name = header_name
20
+
21
+ def configure(self, request: httpx.Request) -> httpx.Request:
22
+ request.headers[self.header_name] = self.api_key
23
+ return request
24
+
25
+ class NoAuth:
26
+ def configure(self, request: httpx.Request) -> httpx.Request:
27
+ return request
ibmrpa_sdk/client.py ADDED
@@ -0,0 +1,139 @@
1
+ import httpx
2
+ from typing import Optional, Any, Dict, Union
3
+ import logging
4
+
5
+ from .config import Settings
6
+ from .auth import AuthStrategy, BearerTokenAuth, ApiKeyAuth, NoAuth
7
+ from .exceptions import (
8
+ IbmRpaHttpError,
9
+ IbmRpaTimeoutError,
10
+ IbmRpaConnectionError,
11
+ IbmRpaRateLimitError,
12
+ IbmRpaError
13
+ )
14
+ from .utils.retry import create_retry_decorator
15
+ from .utils.logging import get_logger
16
+
17
+ # Import endpoint classes (to be implemented)
18
+ # from .endpoints.authentication import Authentication
19
+ # from .endpoints.bots import Bots
20
+ # from .endpoints.projects import Projects
21
+ # from .endpoints.tenant_management import TenantManagement
22
+ # from .endpoints.workspace import Workspace
23
+
24
+ logger = get_logger("ibmrpa_sdk.client")
25
+
26
+ class IbmRpaClient:
27
+ def __init__(
28
+ self,
29
+ base_url: Optional[str] = None,
30
+ token: Optional[str] = None,
31
+ settings: Optional[Settings] = None,
32
+ http_client: Optional[httpx.Client] = None
33
+ ):
34
+ self.settings = settings or Settings()
35
+
36
+ # Override settings if explicitly provided
37
+ if base_url:
38
+ self.settings.base_url = base_url
39
+ if token:
40
+ self.settings.token = token
41
+
42
+ self.settings.validate_setup()
43
+
44
+ # Determine Auth Strategy
45
+ self.auth: AuthStrategy = NoAuth()
46
+ if self.settings.token:
47
+ self.auth = BearerTokenAuth(self.settings.token)
48
+ elif self.settings.api_key:
49
+ self.auth = ApiKeyAuth(self.settings.api_key)
50
+
51
+ # HTTP Client Setup
52
+ self._http = http_client or httpx.Client(
53
+ base_url=self.settings.base_url,
54
+ timeout=self.settings.timeout,
55
+ verify=self.settings.verify_ssl,
56
+ )
57
+
58
+ # Retry Decorator
59
+ self._retry = create_retry_decorator(
60
+ self.settings.retry_max_attempts,
61
+ self.settings.retry_backoff
62
+ )
63
+
64
+ # Initialize Endpoint Categories
65
+ from .endpoints.authentication import Authentication
66
+ from .endpoints.bots import Bots
67
+ from .endpoints.projects import Projects
68
+ from .endpoints.tenant_management import TenantManagement
69
+ from .endpoints.workspace import Workspace
70
+ from .endpoints.process_management import ProcessManagement
71
+
72
+ self.authentication = Authentication(self)
73
+ self.bots = Bots(self)
74
+ self.projects = Projects(self)
75
+ self.tenant = TenantManagement(self)
76
+ self.workspace = Workspace(self)
77
+ self.process = ProcessManagement(self)
78
+
79
+ def request(
80
+ self,
81
+ method: str,
82
+ path: str,
83
+ **kwargs
84
+ ) -> httpx.Response:
85
+
86
+ @self._retry
87
+ def _do_request():
88
+ # Inject Auth
89
+ request = self._http.build_request(method, path, **kwargs)
90
+ request = self.auth.configure(request)
91
+
92
+ try:
93
+ logger.debug(f"Request: {method} {request.url}")
94
+ response = self._http.send(request)
95
+
96
+ # Handling Errors
97
+ if response.is_error:
98
+ self._handle_error(response)
99
+
100
+ return response
101
+
102
+ except httpx.TimeoutException as e:
103
+ logger.error(f"Timeout: {e}")
104
+ raise IbmRpaTimeoutError(f"Request timed out: {e}") from e
105
+ except httpx.NetworkError as e:
106
+ logger.error(f"Network error: {e}")
107
+ raise IbmRpaConnectionError(f"Network happened: {e}") from e
108
+ except IbmRpaError:
109
+ raise
110
+ except Exception as e:
111
+ logger.error(f"Unexpected error: {e}")
112
+ raise IbmRpaError(f"Unexpected error: {e}") from e
113
+
114
+ return _do_request()
115
+
116
+ def _handle_error(self, response: httpx.Response):
117
+ status = response.status_code
118
+ try:
119
+ body = response.json()
120
+ except Exception:
121
+ body = response.text
122
+
123
+ logger.error(f"HTTP Error {status}: {body}")
124
+
125
+ if status == 429:
126
+ raise IbmRpaRateLimitError(status, "Too Many Requests", body)
127
+ elif 400 <= status < 500:
128
+ raise IbmRpaHttpError(status, "Client Error", body)
129
+ elif 500 <= status < 600:
130
+ raise IbmRpaHttpError(status, "Server Error", body)
131
+
132
+ def close(self):
133
+ self._http.close()
134
+
135
+ def __enter__(self):
136
+ return self
137
+
138
+ def __exit__(self, exc_type, exc_value, traceback):
139
+ self.close()
ibmrpa_sdk/config.py ADDED
@@ -0,0 +1,21 @@
1
+ import os
2
+ from typing import Optional
3
+ from pydantic import Field, BaseModel
4
+
5
+ class Settings(BaseModel):
6
+ """
7
+ Configuration settings for the IBM RPA SDK.
8
+ Values are loaded from environment variables with the 'IBMRPA_' prefix
9
+ or passed directly to the constructor.
10
+ """
11
+ base_url: str = Field(default_factory=lambda: os.getenv("IBMRPA_BASE_URL", ""))
12
+ token: Optional[str] = Field(default_factory=lambda: os.getenv("IBMRPA_TOKEN"))
13
+ api_key: Optional[str] = Field(default_factory=lambda: os.getenv("IBMRPA_API_KEY"))
14
+ timeout: float = Field(default_factory=lambda: float(os.getenv("IBMRPA_TIMEOUT", "30.0")))
15
+ verify_ssl: bool = Field(default_factory=lambda: os.getenv("IBMRPA_VERIFY_SSL", "true").lower() == "true")
16
+ retry_max_attempts: int = Field(default_factory=lambda: int(os.getenv("IBMRPA_RETRY_MAX_ATTEMPTS", "3")))
17
+ retry_backoff: float = Field(default_factory=lambda: float(os.getenv("IBMRPA_RETRY_BACKOFF", "0.5")))
18
+
19
+ def validate_setup(self) -> None:
20
+ if not self.base_url:
21
+ raise ValueError("IBMRPA_BASE_URL must be set or provided.")
@@ -0,0 +1 @@
1
+ # Endpoints package
@@ -0,0 +1,80 @@
1
+ from typing import Any, Dict, Optional
2
+ from ..models import JsonDict
3
+
4
+ class Authentication:
5
+ def __init__(self, client):
6
+ self.client = client
7
+
8
+ def list_regions(self) -> JsonDict:
9
+ """
10
+ List all available regions where IBM RPA SaaS servers are deployed.
11
+
12
+ Returns:
13
+ Dict containing region information.
14
+ """
15
+ response = self.client.request(
16
+ "GET",
17
+ "/v2.0/configuration/regions"
18
+ )
19
+ return response.json()
20
+
21
+ def list_tenants_by_user(self, username: str) -> Any:
22
+ """
23
+ Lists all the tenants that a user can access.
24
+
25
+ Args:
26
+ username: The username (email) to search for.
27
+
28
+ Returns:
29
+ List of tenants.
30
+ """
31
+ response = self.client.request(
32
+ "GET",
33
+ "/v2.0/account/tenant",
34
+ params={"UserName": username}
35
+ )
36
+ return response.json()
37
+
38
+ def get_token(
39
+ self,
40
+ grant_type: str = "password",
41
+ username: Optional[str] = None,
42
+ password: Optional[str] = None,
43
+ tenant_id: Optional[str] = None,
44
+ culture: str = "en-US",
45
+ **kwargs
46
+ ) -> JsonDict:
47
+ """
48
+ Get a JSON Web Token (JWT).
49
+
50
+ Args:
51
+ grant_type: Login method type (default 'password').
52
+ username: User email.
53
+ password: User password.
54
+ tenant_id: Optional tenant ID header.
55
+ culture: Language code.
56
+
57
+ Returns:
58
+ Token response containing access_token.
59
+ """
60
+ data = {
61
+ "grant_type": grant_type,
62
+ "culture": culture,
63
+ **kwargs
64
+ }
65
+ if username:
66
+ data["username"] = username
67
+ if password:
68
+ data["password"] = password
69
+
70
+ headers = {}
71
+ if tenant_id:
72
+ headers["tenantId"] = tenant_id
73
+
74
+ response = self.client.request(
75
+ "POST",
76
+ "/v1.0/token",
77
+ data=data,
78
+ headers=headers
79
+ )
80
+ return response.json()
@@ -0,0 +1,76 @@
1
+ from typing import Any, Dict, Optional
2
+ from ..models import JsonDict
3
+
4
+ class Bots:
5
+ def __init__(self, client):
6
+ self.client = client
7
+
8
+ def run_bot(
9
+ self,
10
+ workspace_id: str,
11
+ project_id: str,
12
+ bot_id: str,
13
+ input_variables: Dict[str, Any],
14
+ callback_url: Optional[str] = None
15
+ ) -> JsonDict:
16
+ """
17
+ Triggers a bot to run using IDs.
18
+
19
+ Args:
20
+ workspace_id: ID of the workspace.
21
+ project_id: ID of the project.
22
+ bot_id: ID of the bot.
23
+ input_variables: Dictionary of input variables for the bot.
24
+ callback_url: Optional URL to be called after runtime finishes.
25
+
26
+ Returns:
27
+ Job information (JSON).
28
+ """
29
+ headers = {}
30
+ if callback_url:
31
+ headers["callbackUrl"] = callback_url
32
+
33
+ path = f"/v2.0/workspace/{workspace_id}/projects/{project_id}/bots/{bot_id}"
34
+
35
+ response = self.client.request(
36
+ "POST",
37
+ path,
38
+ json=input_variables,
39
+ headers=headers
40
+ )
41
+ return response.json()
42
+
43
+ def run_bot_by_unique_id(
44
+ self,
45
+ workspace_id: str,
46
+ project_unique_id: str,
47
+ bot_unique_id: str,
48
+ input_variables: Dict[str, Any],
49
+ callback_url: Optional[str] = None
50
+ ) -> JsonDict:
51
+ """
52
+ Triggers a bot to run using Unique IDs (technical names).
53
+
54
+ Args:
55
+ workspace_id: ID of the workspace.
56
+ project_unique_id: Unique ID of the project.
57
+ bot_unique_id: Unique ID of the bot.
58
+ input_variables: Input variables.
59
+ callback_url: Optional callback URL.
60
+
61
+ Returns:
62
+ Job information.
63
+ """
64
+ headers = {}
65
+ if callback_url:
66
+ headers["callbackUrl"] = callback_url
67
+
68
+ path = f"/v2.0/workspace/{workspace_id}/projects/{project_unique_id}/bots/{bot_unique_id}"
69
+
70
+ response = self.client.request(
71
+ "POST",
72
+ path,
73
+ json=input_variables,
74
+ headers=headers
75
+ )
76
+ return response.json()
@@ -0,0 +1,49 @@
1
+ from typing import Any, Dict, Optional
2
+ from ..models import JsonDict
3
+
4
+ class ProcessManagement:
5
+ def __init__(self, client):
6
+ self.client = client
7
+
8
+ def get_process_instance(
9
+ self,
10
+ workspace_id: str,
11
+ process_id: str,
12
+ instance_id: str
13
+ ) -> JsonDict:
14
+ """
15
+ Get information about a process instance.
16
+
17
+ Args:
18
+ workspace_id: Workspace ID.
19
+ process_id: Process ID.
20
+ instance_id: Instance ID.
21
+
22
+ Returns:
23
+ Instance information.
24
+ """
25
+ path = f"/v2.0/workspace/{workspace_id}/process/{process_id}/instance/{instance_id}"
26
+ response = self.client.request("GET", path)
27
+ return response.json()
28
+
29
+ def create_process_instance(
30
+ self,
31
+ workspace_id: str,
32
+ process_id: str,
33
+ payload: Dict[str, Any]
34
+ ) -> JsonDict:
35
+ """
36
+ Create a new instance in a process.
37
+
38
+ Args:
39
+ workspace_id: Workspace ID.
40
+ process_id: Process ID.
41
+ payload: Payload variables for the instance.
42
+
43
+ Returns:
44
+ Created instance ID.
45
+ """
46
+ path = f"/v2.0/workspace/{workspace_id}/process/{process_id}/instance"
47
+ body = {"payload": payload}
48
+ response = self.client.request("POST", path, json=body)
49
+ return response.json()
@@ -0,0 +1,52 @@
1
+ from typing import Any, Dict
2
+ from ..models import JsonDict
3
+
4
+ class Projects:
5
+ def __init__(self, client):
6
+ self.client = client
7
+
8
+ def get_openapi_by_id(
9
+ self,
10
+ workspace_id: str,
11
+ project_id: str
12
+ ) -> JsonDict:
13
+ """
14
+ Get the OpenAPI document for a project by ID.
15
+
16
+ Args:
17
+ workspace_id: Workspace ID.
18
+ project_id: Project ID.
19
+
20
+ Returns:
21
+ OpenAPI document (JSON/YAML in response body).
22
+ """
23
+ path = f"/v2.0/workspace/{workspace_id}/projects/{project_id}/openapi"
24
+ response = self.client.request("GET", path)
25
+ # The documentation says it returns YAML/JSON. We try JSON first.
26
+ try:
27
+ return response.json()
28
+ except Exception:
29
+ # If not JSON (e.g. YAML text), return as dict with content or raw text
30
+ return {"content": response.text}
31
+
32
+ def get_openapi_by_unique_id(
33
+ self,
34
+ workspace_id: str,
35
+ unique_id: str
36
+ ) -> JsonDict:
37
+ """
38
+ Get the OpenAPI document for a project by Unique ID.
39
+
40
+ Args:
41
+ workspace_id: Workspace ID.
42
+ unique_id: Project Unique ID.
43
+
44
+ Returns:
45
+ OpenAPI document.
46
+ """
47
+ path = f"/v2.0/workspace/{workspace_id}/projects/{unique_id}/openapi"
48
+ response = self.client.request("GET", path)
49
+ try:
50
+ return response.json()
51
+ except Exception:
52
+ return {"content": response.text}
@@ -0,0 +1,42 @@
1
+ from typing import Any, Dict, Optional
2
+ from ..models import JsonDict
3
+
4
+ class TenantManagement:
5
+ def __init__(self, client):
6
+ self.client = client
7
+
8
+ def get_tenant(self, tenant_id: str) -> JsonDict:
9
+ """
10
+ Get information about a tenant.
11
+
12
+ Args:
13
+ tenant_id: The ID of the tenant.
14
+
15
+ Returns:
16
+ Tenant information.
17
+ """
18
+ path = f"/v2.0/tenant/{tenant_id}"
19
+ response = self.client.request("GET", path)
20
+ return response.json()
21
+
22
+ def resume_tenant(self, tenant_id: str, culture: str = "en-US") -> None:
23
+ """
24
+ Resume a tenant that was in suspended state.
25
+
26
+ Args:
27
+ tenant_id: Tenant ID.
28
+ culture: Language code.
29
+ """
30
+ path = f"/v2.0/tenant/{tenant_id}/resume"
31
+ self.client.request("PATCH", path, params={"culture": culture})
32
+
33
+ def suspend_tenant(self, tenant_id: str, culture: str = "en-US") -> None:
34
+ """
35
+ Suspend a tenant.
36
+
37
+ Args:
38
+ tenant_id: Tenant ID.
39
+ culture: Language code.
40
+ """
41
+ path = f"/v2.0/tenant/{tenant_id}/suspend"
42
+ self.client.request("PATCH", path, params={"culture": culture})
@@ -0,0 +1,19 @@
1
+ from typing import Any, Dict, List
2
+ from ..models import JsonDict
3
+
4
+ class Workspace:
5
+ def __init__(self, client):
6
+ self.client = client
7
+
8
+ def get_active_workspace(self) -> List[JsonDict]:
9
+ """
10
+ Gets the ID of the active workspace (tenant).
11
+
12
+ Returns:
13
+ List containing workspace information.
14
+ """
15
+ response = self.client.request(
16
+ "GET",
17
+ "/v2.0/workspace"
18
+ )
19
+ return response.json()
@@ -0,0 +1,36 @@
1
+ from typing import Optional, Any
2
+
3
+ class IbmRpaError(Exception):
4
+ """Base exception for all IBM RPA SDK errors."""
5
+ pass
6
+
7
+ class IbmRpaConfigError(IbmRpaError):
8
+ """Configuration related errors."""
9
+ pass
10
+
11
+ class IbmRpaAuthError(IbmRpaError):
12
+ """Authentication failed."""
13
+ pass
14
+
15
+ class IbmRpaTimeoutError(IbmRpaError):
16
+ """Request timed out."""
17
+ pass
18
+
19
+ class IbmRpaConnectionError(IbmRpaError):
20
+ """Network or connection error."""
21
+ pass
22
+
23
+ class IbmRpaHttpError(IbmRpaError):
24
+ """HTTP error response (4xx or 5xx)."""
25
+ def __init__(self, status_code: int, message: str, body: Any = None):
26
+ self.status_code = status_code
27
+ self.body = body
28
+ super().__init__(f"HTTP {status_code}: {message}")
29
+
30
+ class IbmRpaValidationError(IbmRpaError):
31
+ """Data validation error."""
32
+ pass
33
+
34
+ class IbmRpaRateLimitError(IbmRpaHttpError):
35
+ """Rate limit exceeded (429)."""
36
+ pass
@@ -0,0 +1,5 @@
1
+ # Models package
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ # Export generic types for now
5
+ JsonDict = Dict[str, Any]
@@ -0,0 +1,15 @@
1
+ import logging
2
+ from typing import Optional
3
+
4
+ def get_logger(name: str = "ibmrpa_sdk") -> logging.Logger:
5
+ """Configures and returns a logger instance."""
6
+ logger = logging.getLogger(name)
7
+ if not logger.handlers:
8
+ handler = logging.StreamHandler()
9
+ formatter = logging.Formatter(
10
+ '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
11
+ )
12
+ handler.setFormatter(formatter)
13
+ logger.addHandler(handler)
14
+ logger.setLevel(logging.INFO)
15
+ return logger
@@ -0,0 +1,40 @@
1
+ import logging
2
+
3
+ from tenacity import (
4
+ retry,
5
+ stop_after_attempt,
6
+ wait_exponential,
7
+ retry_if_exception_type,
8
+ before_sleep_log
9
+ )
10
+ import httpx
11
+ from ..exceptions import IbmRpaTimeoutError, IbmRpaConnectionError, IbmRpaRateLimitError
12
+ from .logging import get_logger
13
+
14
+ logger = get_logger("ibmrpa_sdk.retry")
15
+
16
+ def create_retry_decorator(max_attempts: int, backoff_factor: float):
17
+ """
18
+ Creates a tenacity retry decorator.
19
+ Retries on:
20
+ - Network/Connection errors
21
+ - Timeouts
22
+ - 5xx Server errors (via httpx.HTTPStatusError checks if we raise them appropriately or check status)
23
+ - 429 Rate Limits
24
+ """
25
+ # Note: We will handle status codes by raising exceptions in the client,
26
+ # so we retry on specific mapped exceptions.
27
+
28
+ return retry(
29
+ stop=stop_after_attempt(max_attempts),
30
+ wait=wait_exponential(multiplier=backoff_factor, min=1, max=60),
31
+ retry=retry_if_exception_type((
32
+ IbmRpaTimeoutError,
33
+ IbmRpaConnectionError,
34
+ IbmRpaRateLimitError,
35
+ httpx.NetworkError,
36
+ httpx.TimeoutException
37
+ )),
38
+ before_sleep=before_sleep_log(logger, logging.WARNING),
39
+ reraise=True
40
+ )
@@ -0,0 +1,255 @@
1
+ Metadata-Version: 2.4
2
+ Name: ibmrpa_sdk
3
+ Version: 0.1.0
4
+ Summary: Unofficial Python SDK for the IBM RPA SaaS REST APIs
5
+ Author: Rodrigo Vitorino
6
+ License-Expression: MIT
7
+ Keywords: ibm,rpa,robotic process automation,sdk,api,httpx
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: httpx>=0.24.0
18
+ Requires-Dist: pydantic>=2.0.0
19
+ Requires-Dist: tenacity>=8.2.0
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
22
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
23
+ Requires-Dist: respx>=0.20.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
25
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
26
+ Requires-Dist: types-requests; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # ibmrpa-sdk
30
+
31
+ Unofficial Python SDK for the **IBM RPA SaaS** REST APIs: authentication, bots, orchestration processes, projects,
32
+ tenants and workspace. Built on `httpx`, `pydantic` and `tenacity`. The client adds the bearer token, retries
33
+ transient failures and turns HTTP errors into exceptions.
34
+
35
+ > **Unofficial.** This project is not affiliated with, endorsed by or supported by IBM. IBM is a trademark of
36
+ > International Business Machines Corporation.
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install ibmrpa-sdk
42
+ ```
43
+
44
+ Requires Python 3.9 or newer. The import name is `ibmrpa_sdk`.
45
+
46
+ ## Configuration
47
+
48
+ The client reads these environment variables, or takes the same values in its constructor:
49
+
50
+ | Variable | Purpose | Default |
51
+ |---|---|---|
52
+ | `IBMRPA_BASE_URL` | API server of your region, scheme and host only | required |
53
+ | `IBMRPA_TOKEN` | `accessToken` returned by `get_token` | no token |
54
+ | `IBMRPA_TIMEOUT` | Timeout per request, in seconds | `30` |
55
+ | `IBMRPA_VERIFY_SSL` | Verify the server TLS certificate | `true` |
56
+ | `IBMRPA_RETRY_MAX_ATTEMPTS` | Attempts on timeouts, connection errors and HTTP 429 | `3` |
57
+ | `IBMRPA_RETRY_BACKOFF` | Exponential backoff multiplier (waits between 1 s and 60 s) | `0.5` |
58
+
59
+ Regions, as returned by `list_regions` in November 2026:
60
+
61
+ | Region | Location | `IBMRPA_BASE_URL` |
62
+ |---|---|---|
63
+ | BR1 | Brazil South | `https://br1api.rpa.ibm.com` |
64
+ | BR2 | Brazil South (BR2) | `https://br2api.rpa.ibm.com` |
65
+ | EU1 | Germany West Central | `https://eu1api.rpa.ibm.com` |
66
+ | US1 | South Central US | `https://us1api.rpa.ibm.com` |
67
+ | AP1 | Southeast Asia | `https://ap1api.rpa.ibm.com` |
68
+ | UK1 | UK South | `https://uk1api.rpa.ibm.com` |
69
+
70
+ `list_regions` returns `apiUrl` values that end in `/v1.0/`. Use only the scheme and host as `base_url`, because the
71
+ SDK adds `/v1.0/...` or `/v2.0/...` to each call.
72
+
73
+ The SDK does not read usernames or passwords. The examples below use `IBMRPA_USERNAME` and `IBMRPA_PASSWORD`, which
74
+ you set yourself. Never hardcode credentials.
75
+
76
+ ## Quickstart
77
+
78
+ ```python
79
+ import os
80
+ from ibmrpa_sdk import IbmRpaClient
81
+
82
+ BASE_URL = os.environ["IBMRPA_BASE_URL"]
83
+ USERNAME = os.environ["IBMRPA_USERNAME"]
84
+
85
+ # The regions, account/tenant and token endpoints do not need a bearer token.
86
+ with IbmRpaClient(base_url=BASE_URL) as anon:
87
+ tenants = anon.authentication.list_tenants_by_user(USERNAME) # [{"id": ..., "name": ...}]
88
+ resp = anon.authentication.get_token(
89
+ username=USERNAME,
90
+ password=os.environ["IBMRPA_PASSWORD"],
91
+ tenant_id=tenants[0]["id"],
92
+ )
93
+ token = resp["accessToken"] # valid for resp["expiresIn"] seconds (about 24 h): reuse it
94
+
95
+ client = IbmRpaClient(base_url=BASE_URL, token=token)
96
+ workspace_id = client.workspace.get_active_workspace()[0]["id"] # workspace ID == tenant ID
97
+
98
+ job = client.bots.run_bot_by_unique_id(
99
+ workspace_id,
100
+ project_unique_id="my-project",
101
+ bot_unique_id="my-bot",
102
+ input_variables={"in_customer": "ACME", "in_order": 12345},
103
+ callback_url="https://example.com/rpa/callback", # optional
104
+ )
105
+ print(job["jobId"], job.get("statusName"))
106
+ ```
107
+
108
+ `client.bots.run_bot(workspace_id, project_id, bot_id, input_variables)` does the same with GUIDs. The keys of
109
+ `input_variables` are the names of the input variables of the bot's script. The API has no job-status endpoint, so
110
+ get the result through `callback_url`, or run the work as an orchestration process (see below).
111
+
112
+ The examples below reuse `client` and `workspace_id`. Call `client.close()` when you are done, or use
113
+ `with IbmRpaClient(...) as client:` to close the connection automatically.
114
+
115
+ ## More examples
116
+
117
+ ### List regions
118
+
119
+ ```python
120
+ from urllib.parse import urlsplit
121
+ from ibmrpa_sdk import IbmRpaClient
122
+
123
+ with IbmRpaClient(base_url="https://br1api.rpa.ibm.com") as anon:
124
+ for region in anon.authentication.list_regions(): # [{"name", "description", "apiUrl"}]
125
+ api = urlsplit(region["apiUrl"])
126
+ print(region["name"], region["description"], f"{api.scheme}://{api.netloc}")
127
+ ```
128
+
129
+ ### Orchestration process: create an instance and poll it
130
+
131
+ ```python
132
+ import time
133
+
134
+ PROCESS_ID = "00000000-0000-0000-0000-000000000000"
135
+
136
+ instance_id = client.process.create_process_instance(
137
+ workspace_id, PROCESS_ID, payload={"customer": "ACME", "priority": "high"}
138
+ )["id"]
139
+
140
+ for _ in range(60): # about 10 minutes
141
+ info = client.process.get_process_instance(workspace_id, PROCESS_ID, instance_id)
142
+ if info.get("statusName") == "done":
143
+ print(info.get("outputs"))
144
+ break
145
+ time.sleep(10)
146
+ ```
147
+
148
+ ### Project OpenAPI document
149
+
150
+ ```python
151
+ doc = client.projects.get_openapi_by_unique_id(workspace_id, "my-project")
152
+ print(doc["content"] if isinstance(doc, dict) and "content" in doc else doc) # YAML text, or parsed JSON
153
+ ```
154
+
155
+ `client.projects.get_openapi_by_id(workspace_id, project_id)` does the same with the project GUID.
156
+
157
+ ### Tenants (requires the Platform administrator role)
158
+
159
+ ```python
160
+ info = client.tenant.get_tenant(workspace_id)
161
+ print(info["name"], "suspended" if info.get("isDeactivated") else "active")
162
+
163
+ # Suspending blocks all use of the tenant. Run these only on purpose:
164
+ # client.tenant.suspend_tenant(workspace_id)
165
+ # client.tenant.resume_tenant(workspace_id)
166
+ ```
167
+
168
+ ### Endpoints without a dedicated method
169
+
170
+ `client.request(method, path, **kwargs)` calls any endpoint with the token, retries and error handling applied.
171
+ Extra keyword arguments go to httpx (`params`, `json`, `data`, `headers`), and it returns an `httpx.Response`:
172
+
173
+ ```python
174
+ projects = client.request("GET", f"/v2.0/workspace/{workspace_id}/projects").json()
175
+ page = client.request(
176
+ "GET", f"/v2.0/workspace/{workspace_id}/process", params={"Search": "billing", "Limit": 50}
177
+ ).json()
178
+ print([p["uniqueId"] for p in projects], page["total"])
179
+ ```
180
+
181
+ ### Errors
182
+
183
+ ```python
184
+ from ibmrpa_sdk.exceptions import (
185
+ IbmRpaConnectionError,
186
+ IbmRpaHttpError,
187
+ IbmRpaRateLimitError,
188
+ IbmRpaTimeoutError,
189
+ )
190
+
191
+ try:
192
+ client.workspace.get_active_workspace()
193
+ except IbmRpaRateLimitError: # HTTP 429 after all retries (a subclass of IbmRpaHttpError)
194
+ print("rate limited, try again later")
195
+ except IbmRpaHttpError as e: # other 4xx and 5xx
196
+ print(e.status_code, e.body) # {"errorMessage": "...", "modelState": {...}}
197
+ except (IbmRpaTimeoutError, IbmRpaConnectionError) as e:
198
+ print("network error:", e)
199
+ ```
200
+
201
+ All exceptions derive from `ibmrpa_sdk.exceptions.IbmRpaError`. A 404 can mean missing permissions, not only a
202
+ missing resource.
203
+
204
+ ### Advanced configuration
205
+
206
+ ```python
207
+ import httpx
208
+ from ibmrpa_sdk import IbmRpaClient, Settings
209
+
210
+ settings = Settings(base_url=BASE_URL, token=token, timeout=60, retry_max_attempts=5)
211
+ with IbmRpaClient(settings=settings) as c:
212
+ print(c.workspace.get_active_workspace())
213
+
214
+ # Your own httpx client (proxies, certificates, limits) is used as is: set base_url and timeout on it too.
215
+ with IbmRpaClient(base_url=BASE_URL, token=token, http_client=httpx.Client(base_url=BASE_URL, timeout=60)) as c:
216
+ print(c.workspace.get_active_workspace())
217
+ ```
218
+
219
+ ## API coverage
220
+
221
+ | API | Methods |
222
+ |---|---|
223
+ | Authentication | `list_regions()`, `list_tenants_by_user(username)`, `get_token(...)` |
224
+ | Bots | `run_bot(...)`, `run_bot_by_unique_id(...)` |
225
+ | Process Management | `create_process_instance(...)`, `get_process_instance(...)` |
226
+ | Projects | `get_openapi_by_id(...)`, `get_openapi_by_unique_id(...)` |
227
+ | Tenant Management | `get_tenant(...)`, `suspend_tenant(...)`, `resume_tenant(...)` |
228
+ | Workspace | `get_active_workspace()` |
229
+
230
+ Not covered yet (use `client.request`): list processes, get a process, list projects, create a tenant,
231
+ `DELETE /v2.0/tenant/{tenantId}`, and SSO login with the `oidc-access-token` header.
232
+
233
+ ## Known limitations
234
+
235
+ - The endpoint methods of `AsyncIbmRpaClient` do not work yet and raise
236
+ `AttributeError: 'coroutine' object has no attribute 'json'`. `await client.request(...)` works:
237
+
238
+ ```python
239
+ import asyncio
240
+ from ibmrpa_sdk import AsyncIbmRpaClient
241
+
242
+ async def main():
243
+ async with AsyncIbmRpaClient(base_url=BASE_URL, token=token) as aclient:
244
+ print((await aclient.request("GET", "/v2.0/workspace")).json())
245
+
246
+ asyncio.run(main())
247
+ ```
248
+
249
+ - Retries also apply to `POST` requests that time out, so a timed-out `run_bot` call can start the bot twice. Set
250
+ `IBMRPA_RETRY_MAX_ATTEMPTS=1` for critical calls.
251
+ - `get_openapi_*` can return a `dict`, a `str` or `{"content": text}`, depending on the response.
252
+
253
+ ## License
254
+
255
+ MIT
@@ -0,0 +1,21 @@
1
+ ibmrpa_sdk/__init__.py,sha256=dRWo5hkJVt-lhIRArx-kmTc0PNftj3Y_ZWb3lCKb0DI,224
2
+ ibmrpa_sdk/async_client.py,sha256=L1iZnWl0a8sz5-SPXfDav1nYJ85pgARbWM6-ZzME8OE,4545
3
+ ibmrpa_sdk/auth.py,sha256=OnU-7BDLRFH3z37kbn_i3tBVj-DFa8TygV1jZRVeadg,842
4
+ ibmrpa_sdk/client.py,sha256=kgCK7I06eVymUz7t-3EZ04sTcTSF8ma7HnRD_uH0KvY,4759
5
+ ibmrpa_sdk/config.py,sha256=rFpdhA23VuW82cjYLi09n26c88eIE7JKkZpMf5i6hao,1127
6
+ ibmrpa_sdk/exceptions.py,sha256=NRibh8wx5-HAPobsiBMDfZEABVgYlch-gskTjpOjFMk,953
7
+ ibmrpa_sdk/endpoints/__init__.py,sha256=3jMAPXaBA3lX9DVaOgkRJPzbfHUvfqM8k5XMlA69mC0,21
8
+ ibmrpa_sdk/endpoints/authentication.py,sha256=FiVOnJED_IiQgMygwMYe3YZ0pPj5KXiGAoTW_ngk5mw,2212
9
+ ibmrpa_sdk/endpoints/bots.py,sha256=hQK5HYtXOvrwONBYqQ-eF2DlubOGw8NFtgT7lnbdrHY,2291
10
+ ibmrpa_sdk/endpoints/process_management.py,sha256=A9K-dbOMyfPOvOgQ2baIzNVha5tbB2Kt--swUm9DuAk,1445
11
+ ibmrpa_sdk/endpoints/projects.py,sha256=Ejklbfls1plTnJ-TPrfP8sf_eSBFbGMsWW9zVMa_V4k,1594
12
+ ibmrpa_sdk/endpoints/tenant_management.py,sha256=m0rPD89ptPue5X3YL6VmAq5Vp--5o0sODLz-MAfcRwU,1287
13
+ ibmrpa_sdk/endpoints/workspace.py,sha256=1FlkIQn6hb_kG8gbLzZxMIFrLrfUU3sI42qA7W6IDbA,503
14
+ ibmrpa_sdk/models/__init__.py,sha256=TKVbL3jZdklYJ3njpfQ7bwJnM4Fl8u1T3VQ7hPgq8Pg,125
15
+ ibmrpa_sdk/utils/logging.py,sha256=Uz2AsWDXCC_foIdeTP0jsRc4hzXuGr26qJSL5-Ezkpk,525
16
+ ibmrpa_sdk/utils/retry.py,sha256=ExPibsM93i_QLH57gn_vn96o8HD_8m6QXgsbnZNcNgs,1263
17
+ ibmrpa_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=V5I1-6Xgzmr0ek104B9DwnoK77w6HMXac4qsLhnHogU,1094
18
+ ibmrpa_sdk-0.1.0.dist-info/METADATA,sha256=IROQNa5CNUpbnsjPemKkSc9OpLGBVwZeff-6AJY8pLo,9754
19
+ ibmrpa_sdk-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
20
+ ibmrpa_sdk-0.1.0.dist-info/top_level.txt,sha256=9uQUnT5hn9R1trKPn9re7gEIqn8EUhREqKDUX3Gs_oY,11
21
+ ibmrpa_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rodrigo Vitorino
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ ibmrpa_sdk