### Automating SAP Queries (SQ01) Source: https://github.com/21010/rpa-sap/blob/main/README.md Use SQ01 helper to start, execute, and export SAP queries to a local file. ```python from rpa_sap.lib.SQ01 import SQ01 # Initialize SQ01 helper sq01 = SQ01(session) # Navigate to the query, providing a user group and variant sq01.start_query(query_name="MY_QUERY", user_group="MY_GROUP", variant_name="DEFAULT") # Execute the query sq01.execute_query() # Export the results directly to a local file sq01.to_local_file(folder_path="C:\\Exports", file_name="query_results.xls", file_type="xls") ``` -------------------------------- ### Install rpa-sap via pip Source: https://github.com/21010/rpa-sap/blob/main/README.md Install the package using pip. Requires Python >= 3.10 and SAP GUI Scripting enabled. ```sh pip install rpa-sap ``` -------------------------------- ### start_query method signature Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Starts an SQ01 query with optional query area, user group, and variant. Raises ValueError for invalid query_area, SapElementNotFoundError for missing user group or variant, and Exception for SAP errors. ```python def start_query( self, query_name: str, query_area: Literal["Standard", "Global"] | None, user_group: str | None = None, variant_name: str | None = None, ): ``` -------------------------------- ### start_query Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Starts an SQ01 query by entering the query name, optionally selecting a query area, user group, and variant. It runs the SAP transaction and handles the full UI flow, raising errors if the query fails. ```APIDOC ## start_query ### Description Starts an SQ01 query by entering the query name, optionally selecting a query area, user group, and variant. It runs the SAP transaction and handles the full UI flow, raising errors if the query fails. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `query_name` (str) - Required - Query name entered into `CTXT_QUERY_NAME`. - `query_area` (Literal["Standard", "Global"] | None) - Required (positional) - Query area to switch to; `None` skips the area change. Any other string raises built-in `ValueError(f"Invalid query_area: '{query_area}'. Must be 'Standard' or 'Global'")`. - `user_group` (str | None) - Optional - User group to select; `None` skips the user-group flow. - `variant_name` (str | None) - Optional - Variant to execute with; `None` executes directly via `BTN_EXECUTE`. ### Request Example ```python start_query( query_name="MyQuery", query_area="Standard", user_group="MyGroup", variant_name="MyVariant" ) ``` ### Response #### Success Response (200) - **Return type:** `None` #### Response Example ```python None ``` ### Error Handling - Throws `ValueError` (invalid `query_area`), `SapElementNotFoundError` (user group not found / variant not found), plain `Exception` (SAP error message in status bar), plus `SapTransactionError`/`SapSessionError` from `run_transaction`. ``` -------------------------------- ### Executing a BAPI via RFC Source: https://github.com/21010/rpa-sap/blob/main/README.md Use RfcConnection to call a BAPI and extract specific import parameters and tables. The example shows accessing returned structures and tables. ```python from rpa_sap import RfcConnection with RfcConnection( connection_string="My SAP System", user_id="user_id", password="password" ) as rfc: results = rfc.call_bapi( bapi_name="BAPI_USER_GET_DETAIL", import_params={"USERNAME": "USERNAME"}, extract_imports=["ADDRESS"], extract_tables=["ACTIVITYGROUPS"] ) # Access the returned structures and tables address_data = results.get("ADDRESS") roles = results.get("ACTIVITYGROUPS") print(f"User Full Name: {address_data.get('FULLNAME')}") print(f"Number of roles: {len(roles)}") ``` -------------------------------- ### Integrating via SAP OData (REST) Source: https://github.com/21010/rpa-sap/blob/main/README.md Use ODataClient with authentication strategies (Basic, OAuth2) to query entity sets, get DataFrames, and create entities with automatic CSRF token handling. ```python from rpa_sap.core.odata import ODataClient, BasicAuthStrategy # 1. Choose your authentication strategy auth = BasicAuthStrategy("USERNAME", "password") # Or use OAuth2: auth = OAuth2Strategy("my-bearer-token") # 2. Initialize the client client = ODataClient("https://mysap.example.com/sap/opu/odata/sap/API_USER_SRV", auth) # 3. Query an EntitySet and get a Pandas DataFrame df = client.get_dataframe("UserSet", select=["UserID", "FullName"], top=50) print(df.head()) # 4. Create a new Entity (CSRF token is fetched automatically) new_user = {"UserID": "NEW_RPA", "FullName": "RPA Bot User"} response = client.post("UserSet", payload=new_user) print("Created:", response) ``` -------------------------------- ### Run unit tests with pytest Source: https://github.com/21010/rpa-sap/blob/main/README.md Executes the unit test suite located in tests/unit/. These tests mock SAP GUI COM objects and do not require a live SAP installation or active connection. ```sh uv run pytest tests/unit ``` -------------------------------- ### open_new_session(...) Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/connection.md Opens a new SAP GUI session and returns a fully logged-in SapSession. It handles starting SAP GUI if needed, retries on failure, and optionally establishes an eager RFC connection for headless operations. ```APIDOC ## open_new_session(...) ### Description Opens a new SAP GUI session and returns a fully logged-in SapSession. It handles starting SAP GUI if needed, retries on failure, and optionally establishes an eager RFC connection for headless operations. ### Method Function call ### Signature ```python def open_new_session( self, connection_string: str, user_id: str, password: str | None = None, client: str = "900", language: str = "EN", timeout: int = 15, step: int = 1, ) -> SapSession: ``` ### Parameters - **connection_string** (str) - Required - Exact name of the connection as defined in SAP Logon (e.g., `"S4HANA Prod"`) or a direct connection string (e.g., `"/H/192.168.1.1/S/3200"`). - **user_id** (str) - Required - SAP user name. - **password** (str | None) - Optional - If `None`, login is assumed to be handled by SSO (no credentials are typed in the GUI; eager RFC is skipped). - **client** (str) - Optional - SAP client (mandant) used for the GUI login and the eager RFC connection. Default: `"900"`. - **language** (str) - Optional - Logon language used for the GUI login and the eager RFC connection. Default: `"EN"`. - **timeout** (int) - Optional - Seconds to wait for the SAP session to open before giving up. Default: `15`. - **step** (int) - Optional - Polling interval (seconds) between connection attempts. Default: `1`. ### Return Type `SapSession` — a fully logged-in session. ### Behavior 1. Checks `_ProcessManager.is_sap_running()`. If SAP GUI is not running, launches `C:/Program Files (x86)/SAP/FrontEnd/SAPgui/SAPgui.exe` with `connection_string` as argument and sleeps 4 s. 2. Polls every `step` seconds until `timeout`; each iteration calls `_initialize_engine()` and then either reuses the last connection the freshly started `SAPgui.exe` opened (`self.connections[...Count - 1]`, first child session) or, if SAP was already running, calls `self.application.OpenConnectionByConnectionString(connection_string, True)` and takes `connection.Children(0)`. 3. On any exception, if SAP was expected to be running, it calls `close_sap_logon()`, sleeps 2 s, restarts `SAPgui.exe`, waits 4 s, and retries. 4. If the loop exhausts `timeout`: raises `SapConnectionError("Timeout while waiting for SAP session to open.")`. 5. If `password` is truthy, eagerly builds a headless `RfcConnection(connection_string, user_id, password, client, language)` and stores it as `sap_session._rfc_client` (wrapped in try/except; on failure a `UserWarning` is emitted and the GUI session is still returned). This avoids keeping plaintext passwords in memory longer than needed and makes `session.rfc` work without re-connecting. 6. Calls `_perform_login(...)` and returns the `SapSession`. ### Throws - `SapProcessError("Failed to start C:/Program Files (x86)/SAP/FrontEnd/SAPgui/SAPgui.exe")` if the SAP GUI binary cannot be launched. - `SapConnectionError("Timeout while waiting for SAP session to open.")` on timeout. - `SapConnectionError` from `_perform_login` if the status bar shows an error message (`status.type == "E"`) or if `com_session` is unavailable. ``` -------------------------------- ### Run integration tests with pytest Source: https://github.com/21010/rpa-sap/blob/main/README.md Executes the integration test suite located in tests/integration/. These tests connect to a live SAP environment and require SAP GUI to be installed, running, and accessible. Tests are marked with @pytest.mark.integration. ```sh uv run pytest -m "integration" ``` -------------------------------- ### Basic query into a DataFrame Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Uses ODataClient with BasicAuthStrategy to query an entity set and return a pandas DataFrame. The example selects specific fields, applies a filter, and limits to 50 records. ```python from rpa_sap.core.odata import ODataClient, BasicAuthStrategy auth = BasicAuthStrategy("USERNAME", "password") client = ODataClient( "https://mysap.example.com/sap/opu/odata/sap/API_USER_SRV", auth, ) df = client.get_dataframe( "UserSet", select=["UserID", "FullName", "Email"], filter_query="UserID eq 'NEW_RPA'", top=50, ) print(df.head()) ``` -------------------------------- ### get method signature Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Signature for the get method that performs GET requests on entity sets with optional select, filter, and top parameters. ```python def get( self, entity_set: str, select: Optional[List[str]] = None, filter_query: Optional[str] = None, top: Optional[int] = None, ) -> List[Dict[str, Any]]: ``` -------------------------------- ### Open a new SAPGUI session with ConnectionManager Source: https://github.com/21010/rpa-sap/blob/main/README.md Creates a new SAP session using the exact connection name from SAP Logon or a direct connection string. Requires user credentials, client, and language. ```python from rpa_sap import ConnectionManager manager = ConnectionManager() session = manager.open_new_session( connection_string="My SAP System", # Exact name from SAP Logon user_id="user_id", password="password", client="100", language="EN" ) ``` -------------------------------- ### ODataClient.get_dataframe Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Executes a GET request and returns the results as a Pandas DataFrame. Forwards all keyword arguments to the get method. ```APIDOC ## ODataClient.get_dataframe ### Description Executes a GET request and returns the results as a Pandas DataFrame. Forwards all keyword arguments to the get method. ### Method GET ### Endpoint `{base_url}/{entity_set}` ### Parameters #### Path Parameters - **entity_set** (str) - Required - Entity set name. #### Query Parameters - **$format** (string) - Required - Set to `json`. - **$select** (string) - Optional - Comma-separated field names from `select` parameter. - **$filter** (string) - Optional - Raw `$filter` expression from `filter_query` parameter. - **$top** (integer) - Optional - Row limit from `top` parameter. ### Request Example ``` GET {base_url}/{entity_set}?$format=json&$select=field1,field2&$filter=...&$top=10 ``` ### Response #### Success Response (200) - **d.results** (array) - List of entity dictionaries. #### Response Example ```json { "d": { "results": [ { "field1": "value1", "field2": "value2" } ] } } ``` ### Errors - **SapODataError** - Thrown for any `requests.RequestException`: "GET request failed for entity set '{entity_set}': {e}" ``` -------------------------------- ### get_property: Get arbitrary COM property Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/ui-automation.md Gets an arbitrary COM property from the element. Requires field_id (element path) and property_name (COM property to retrieve). ```python def get_property(self, field_id: str, property_name: str) -> Any: """Gets an arbitrary COM property from the element.""" return getattr(self._get_object(field_id), property_name) ``` -------------------------------- ### Error handling for SQ01 variant/user-group problems Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Wraps start_query in try/except to catch SapElementNotFoundError for missing variant or user group, ValueError for bad query_area argument, and generic exceptions for SAP-reported errors. Useful for diagnosing configuration issues. ```python from rpa_sap import ConnectionManager, SQ01, SapElementNotFoundError manager = ConnectionManager() session = manager.open_new_session("S4HANA Prod", "rpa_user", "secret") sq01 = SQ01(session) try: sq01.start_query( query_name="MY_QUERY", query_area="Standard", user_group="TYPO_GROUP", variant_name="MISSING_VARIANT", ) except SapElementNotFoundError as e: print("Variant or user group problem:", e) except ValueError as e: print("Bad query_area argument:", e) except Exception as e: print("SAP reported an error:", e) manager.close_session(session) manager.close_sap_logon() ``` -------------------------------- ### get_property Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/ui-automation.md Gets an arbitrary COM property from the element. ```APIDOC ## get_property ### Description Gets an arbitrary COM property from the element. ### Method `get_property(self, field_id: str, property_name: str) -> Any` ### Parameters - `field_id` (str) - Required - Element path. - `property_name` (str) - Required - COM property to retrieve. ### Returns Any - The value of the specified property. ``` -------------------------------- ### get_dataframe method Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Executes a GET request and returns results as a Pandas DataFrame. ```python def get_dataframe(self, entity_set: str, **kwargs) -> pd.DataFrame: """Executes a GET request and returns the results as a Pandas DataFrame.""" results = self.get(entity_set, **kwargs) return pd.DataFrame(results) ``` -------------------------------- ### ODataClient __init__ constructor Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Initializes the client with base URL and auth strategy, creates a requests.Session, applies the strategy, and sets csrf_token to None. ```python def __init__(self, base_url: str, auth_strategy: AuthStrategy): self.base_url = base_url.rstrip("/") self.auth_strategy = auth_strategy self.session = requests.Session() self.auth_strategy.configure_session(self.session) self.csrf_token: Optional[str] = None ``` -------------------------------- ### RfcConnection __init__ method Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/rfc.md Constructor that initializes the RFC connection with connection string, user credentials, client, and language. Calls _connect() immediately, raising SapSessionError on failure. ```python def __init__( self, connection_string: str, user_id: str, password: str, client: str = "900", language: str = "EN", ): ``` -------------------------------- ### run_transaction(self, transaction_code: str) Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/session.md Runs an SAP transaction. No need to add '/n' or go back to the start screen. ```APIDOC ## `run_transaction(self, transaction_code: str)` ### Description Runs an SAP transaction. No need to add '/n' or go back to the start screen. ### Method `run_transaction` ### Parameters - **transaction_code** (str) - Required - SAP transaction code, e.g. `"ME32L"` or `"SQ01"`. No `/n` prefix needed. ### Return Type `None` ### Throws - `SapSessionError` if `com_session` is `None` - `SapTransactionError` when the status bar shows a message of type `"E"` after `StartTransaction` ``` -------------------------------- ### SQ01 class constructor Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Initializes the SQ01 class with an active SapSession. The interactor is captured at construction. ```python class SQ01: def __init__(self, sap_session: SapSession): self.sap_session = sap_session self.interactor = sap_session.interactor ``` -------------------------------- ### fetch_csrf_token method Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Fetches and caches the X-CSRF-Token from the SAP Gateway via GET request. Raises SapODataError if token missing or request fails. ```python def fetch_csrf_token(self) -> str: """Fetches and caches the X-CSRF-Token from the SAP Gateway.""" headers = {"X-CSRF-Token": "Fetch"} try: response = self.session.get(self.base_url, headers=headers) response.raise_for_status() token = response.headers.get("x-csrf-token") if not token: raise SapODataError( "Failed to fetch CSRF token from SAP OData service." ) self.csrf_token = token return token except requests.RequestException as e: raise SapODataError(f"Error fetching CSRF token: {e}") ``` -------------------------------- ### ODataClient.__init__ Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Initializes an ODataClient instance with the given base URL and authentication strategy. Creates a requests.Session, applies the authentication strategy, and initializes the CSRF token to None. ```APIDOC ## ODataClient.__init__ ### Description Initializes an ODataClient instance with the given base URL and authentication strategy. Creates a requests.Session, applies the authentication strategy, and initializes the CSRF token to None. ### Method Constructor ### Signature ```python def __init__(self, base_url: str, auth_strategy: AuthStrategy): ``` ### Parameters - **base_url** (str) - Required - Service root URL (trailing slashes are stripped), e.g. `"https://mysap.example.com/sap/opu/odata/sap/API_USER_SRV"`. - **auth_strategy** (AuthStrategy) - Required - One of `BasicAuthStrategy`, `OAuth2Strategy`, `NoAuthStrategy` (or any `AuthStrategy` subclass). ### Side Effects - Creates a `requests.Session`. - Applies the authentication strategy immediately. - Initializes `csrf_token = None` (fetched lazily on first state-changing request). ``` -------------------------------- ### SapSession.__init__ Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/session.md Initializes a new SapSession instance with the provided COM session, connection, and optional SAP functions. Normally obtained from ConnectionManager methods rather than constructed directly. ```APIDOC ## SapSession.__init__ ### Description Initializes a new SapSession instance with the provided COM session, connection, and optional SAP functions. Normally obtained from ConnectionManager methods rather than constructed directly. ### Method Constructor ### Signature ```python SapSession( com_session: win32com.client.CDispatch | None, com_connection: win32com.client.CDispatch | None = None, sap_functions: win32com.client.CDispatch | None = None, ) ``` ### Parameters - **com_session** (win32com.client.CDispatch | None) - Required - The COM session object (typically `connection.Children(0)`). - **com_connection** (win32com.client.CDispatch | None) - Optional - The COM connection object the session belongs to; used by `ConnectionManager.close_session`. - **sap_functions** (win32com.client.CDispatch | None) - Optional - Optional `SAP.Functions` COM handle. Stored but not used by any SapSession method in the current source. ### Side Effects Builds `self.interactor = ElementInteractor(self)`. ### Notes Normally you obtain instances from `ConnectionManager.open_new_session()` / `activate_session()` rather than constructing them directly. ``` -------------------------------- ### ODataClient.get Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Performs a GET request to the specified entity set with optional query parameters. Returns the OData v2 'd.results' array as a list of entity dictionaries. ```APIDOC ## ODataClient.get ### Description Performs a GET request to the specified entity set with optional query parameters. Returns the OData v2 'd.results' array as a list of entity dictionaries. ### Method GET ### Endpoint `{base_url}/{entity_set}` ### Parameters #### Path Parameters - **entity_set** (str) - Required - Entity set name (e.g., `'UserSet'`). Appended to `base_url`. #### Query Parameters - **$format** (string) - Required - Set to `json`. - **$select** (string) - Optional - Comma-separated field names from `select` parameter. - **$filter** (string) - Optional - Raw `$filter` expression from `filter_query` parameter. - **$top** (integer) - Optional - Row limit from `top` parameter. ### Request Example ``` GET {base_url}/{entity_set}?$format=json&$select=field1,field2&$filter=...&$top=10 ``` ### Response #### Success Response (200) - **d.results** (array) - List of entity dictionaries. #### Response Example ```json { "d": { "results": [ { "field1": "value1", "field2": "value2" } ] } } ``` ### Errors - **SapODataError** - Thrown for any `requests.RequestException`: "GET request failed for entity set '{entity_set}': {e}" ``` -------------------------------- ### ODataClient.fetch_csrf_token Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Fetches and caches the X-CSRF-Token from the SAP Gateway. Performs a GET request to the base URL with the header 'X-CSRF-Token: Fetch' and reads the token from the response header. ```APIDOC ## ODataClient.fetch_csrf_token ### Description Fetches and caches the X-CSRF-Token from the SAP Gateway. Performs a GET request to the base URL with the header 'X-CSRF-Token: Fetch' and reads the token from the response header. ### Method GET ### Endpoint `{base_url}` ### Headers - **X-CSRF-Token** (string) - Required - Set to `Fetch`. ### Response #### Success Response - **x-csrf-token** (string) - The fetched token, also cached on `self.csrf_token`. #### Response Example ``` ``` ### Errors - **SapODataError** - Thrown when the response has no token header: "Failed to fetch CSRF token from SAP OData service." - **SapODataError** - Thrown for any `requests.RequestException`: "Error fetching CSRF token: {e}" ``` -------------------------------- ### to_local_file method signature Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Exports query results to a local file. Maps file_type to encoding code: 'xls' to '0000', 'csv' to '0004', anything else to '0000'. Raises Exception if the status bar does not contain 'Download'. ```python def to_local_file(self, folder_path: str, file_name: str, file_type: str = "xls"): ``` -------------------------------- ### Basic transaction with context manager Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/session.md Opens a new SAP session, runs a transaction using the context manager, and demonstrates raw COM access via findById. Requires a valid SAP connection and user credentials. ```python from rpa_sap import ConnectionManager manager = ConnectionManager() session = manager.open_new_session("S4HANA Prod", "rpa_user", "secret", client="100") with session.transaction("ME32L"): session.interactor.set_text("wnd[0]/usr/ctxtRM06E-EBELN", "4500000001") session.interactor.press_enter() print(session.info) # dict of session details print(session.id) # COM session id element = session.findById("wnd[0]/tbar[0]/okcd") element.text = "MM03" element.sendVKey(0) # raw COM usage via findById manager.close_session(session) manager.close_sap_logon() ``` -------------------------------- ### Basic open and cleanup with ConnectionManager Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/connection.md Opens a new SAP session with connection string, user credentials, client, language, and timeout. Prints the session SID, then closes the session and SAP Logon. ```python from rpa_sap import ConnectionManager manager = ConnectionManager() session = manager.open_new_session( connection_string="S4HANA Prod", user_id="rpa_user", password="secret", client="100", language="EN", timeout=30, ) print(session.info["sid"]) manager.close_session(session) manager.close_sap_logon() ``` -------------------------------- ### BaseExtractor.to_array Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/data-extractors.md Abstract method that subclasses implement to extract SAP control data into an array-like structure. Users call this on concrete extractor instances to get raw data. ```APIDOC ## BaseExtractor.to_array ### Description Abstract method that subclasses implement to extract SAP control data into an array-like structure. Users call this on concrete extractor instances to get raw data. ### Method `to_array(self, field_id: str, **kwargs) -> Any` ### Parameters - **field_id** (str) - Required - Identifier of the SAP control field to extract. - **kwargs** - Optional - Additional extraction options passed to the underlying implementation. ### Returns - **Any** - Array-like structure containing the extracted data. ``` -------------------------------- ### SapSession.__init__ constructor Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/session.md Initializes a SapSession with COM session, connection, and optional SAP functions. Builds an ElementInteractor instance. Normally obtained from ConnectionManager methods rather than constructed directly. ```python def __init__( self, com_session: win32com.client.CDispatch | None, com_connection: win32com.client.CDispatch | None = None, sap_functions: win32com.client.CDispatch | None = None, ): self.com_session = com_session self.com_connection = com_connection self.sap_functions = sap_functions self.interactor = ElementInteractor(self) ``` -------------------------------- ### ConnectionManager __init__ method Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/connection.md Initializes the ConnectionManager instance. No constructor options are required; sap_gui and application COM handles are lazily initialized by _initialize_engine(). ```python def __init__(self): self.sap_gui = None self.application = None ``` -------------------------------- ### BaseExtractor.to_dataframe Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/data-extractors.md Abstract method that subclasses implement to extract SAP control data into a pandas DataFrame. Users call this on concrete extractor instances to get tabular data. ```APIDOC ## BaseExtractor.to_dataframe ### Description Abstract method that subclasses implement to extract SAP control data into a pandas DataFrame. Users call this on concrete extractor instances to get tabular data. ### Method `to_dataframe(self, field_id: str, **kwargs) -> DataFrame` ### Parameters - **field_id** (str) - Required - Identifier of the SAP control field to extract. - **kwargs** - Optional - Additional extraction options passed to the underlying implementation. ### Returns - **DataFrame** - pandas DataFrame containing the extracted data. ``` -------------------------------- ### execute_query Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Presses the Execute button to run the query. Returns `None` and throws `SapElementNotFoundError` if the button cannot be resolved. ```APIDOC ## execute_query ### Description Presses the Execute button to run the query. Returns `None` and throws `SapElementNotFoundError` if the button cannot be resolved. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python execute_query() ``` ### Response #### Success Response (200) - **Return type:** `None` #### Response Example ```python None ``` ### Error Handling - Throws `SapElementNotFoundError` if the button cannot be resolved. ``` -------------------------------- ### OAuth2Strategy.__init__ Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Constructor for OAuth2Strategy, storing a Bearer token for authentication. ```APIDOC ## OAuth2Strategy.__init__ ### Description Constructor for OAuth2Strategy, storing a Bearer token for authentication. ### Method __init__ ### Signature `def __init__(self, token: str):` ### Parameters - **token** (str) - Required - Bearer token. ### Returns None ``` -------------------------------- ### execute_query method Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Presses the Execute button (wnd[0]/tbar[1]/btn[8]). Returns None. Throws SapElementNotFoundError if the button cannot be resolved. ```python def execute_query(self): self.interactor.press_button(SQ01Locators.BTN_EXECUTE) ``` -------------------------------- ### ConnectionManager.__init__ Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/connection.md Initializes a new ConnectionManager instance. No constructor options are required; COM handles are lazily initialized. ```APIDOC ## ConnectionManager.__init__ ### Description Initializes a new ConnectionManager instance. No constructor options are required; COM handles are lazily initialized. ### Method Constructor ### Signature ```python def __init__(self): ``` ### Parameters None ### Returns None ``` -------------------------------- ### run_transaction method Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/session.md Runs an SAP transaction using the provided transaction code. No '/n' prefix or return to start screen is needed. Raises SapSessionError if com_session is None, and SapTransactionError if the status bar shows a message of type 'E' after StartTransaction. ```python def run_transaction(self, transaction_code: str): """ Runs SAP transaction. There is no need to add "/n" or go back to the start screen. """ if self.com_session is None: raise SapSessionError("com_session is not available.") self.com_session.StartTransaction(transaction_code) status = self.interactor.get_status_bar_message() if status.type == "E": raise SapTransactionError(f"{status.type} : {status.text}") ``` -------------------------------- ### _perform_login method signature Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/connection.md Private method that automates the GUI logon process. Fills the username, password (if provided), client, and language fields, sends the Enter key, handles the multiple logon dialog if it appears, and checks the status bar for errors. Raises SapConnectionError if the status bar shows an error type 'E'. ```python def _perform_login( self, sap_session: SapSession, user_id: str, password: str | None, client: str, language: str, ): ``` -------------------------------- ### GuiTableControl to DataFrame with error handling Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/data-extractors.md Extracts data from a SAP GUI TableControl into a DataFrame or array, with error handling for missing controls. The example uses entire_table=False to only read visible rows. Requires an open session and a GuiTableControl object. ```python from rpa_sap import ConnectionManager, GuiTableControl from rpa_sap.lib.data_extractors import GuiTableControlExtractor from rpa_sap.exceptions import SapElementNotFoundError manager = ConnectionManager() session = manager.open_new_session("S4HANA Prod", "rpa_user", "secret") table = GuiTableControl(session) extractor = GuiTableControlExtractor(table) try: df = extractor.to_dataframe( "wnd[0]/usr/tblSAPMV13ATCTRL_FAST_ENTRY", entire_table=False, # only visible rows this time ) print(df.shape) array = extractor.to_array("wnd[0]/usr/tblSAPMV13ATCTRL_FAST_ENTRY") print(array) except SapElementNotFoundError as e: print("Control not found:", e) manager.close_session(session) manager.close_sap_logon() ``` -------------------------------- ### Basic GridView reading: count rows/columns, get current cell and cell value Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/gridview.md Connects to an SAP session and reads grid metadata and cell values using GridView methods. Requires a valid session and grid control ID (GID). ```python from rpa_sap import ConnectionManager, GridView manager = ConnectionManager() session = manager.open_new_session("S4HANA Prod", "rpa_user", "secret") grid = GridView(session) GID = "wnd[0]/usr/cntlGRID1/shellcont/shell" print("rows:", grid.count_rows(GID), "columns:", grid.count_columns(GID)) print("current cell value:", grid.get_current_cell_value(GID)) print("current address:", grid.get_current_cell(GID).row, grid.get_current_cell(GID).column) value = grid.get_cell_value(GID, row_index=3, column_index=1) print("cell(3,1):", value) ``` -------------------------------- ### Basic SQ01 query execution and export Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Connects to SAP, runs an SQ01 query, and exports results to a local file. The file_type parameter selects the SAP export encoding code (0000 = xls-like, 0004 = csv-like) and is not used as a file extension. Export verification is heuristic: the status bar must contain "Download" or to_local_file raises. ```python from rpa_sap import ConnectionManager, SQ01 manager = ConnectionManager() session = manager.open_new_session("S4HANA Prod", "rpa_user", "secret") sq01 = SQ01(session) sq01.start_query( query_name="MY_QUERY", query_area="Global", user_group="MY_GROUP", variant_name="DEFAULT", ) sq01.execute_query() sq01.to_local_file( folder_path=r"C:\Exports", file_name="query_results.xls", file_type="xls", ) manager.close_session(session) manager.close_sap_logon() ``` -------------------------------- ### post() method implementation Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Executes a POST request to create a new OData entity. Automatically handles CSRF token requirements by calling _get_csrf_headers() first. Returns data.get("d", {}) (the created/returned entity wrapper, or {}). Throws SapODataError for any requests.RequestException; SapODataError from _get_csrf_headers/fetch_csrf_token propagates as-is. ```python def post(self, entity_set: str, payload: Dict[str, Any]) -> Dict[str, Any]: """ Executes a POST request to create a new OData entity. Automatically handles CSRF token requirements. """ url = f"{self.base_url}/{entity_set}" headers = self._get_csrf_headers() try: response = self.session.post(url, json=payload, headers=headers) response.raise_for_status() data = response.json() return data.get("d", {}) except requests.RequestException as e: raise SapODataError( f"POST request failed for entity set '{entity_set}': {e}" ) ``` -------------------------------- ### RfcConnection(connection_string, user_id, password, client="900", language="EN") Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/configuration.md Constructor for the RfcConnection class. Connects immediately in the constructor. ```APIDOC ## RfcConnection(connection_string, user_id, password, client="900", language="EN") ### Description Constructor for the RfcConnection class. Connects immediately in the constructor. ### Constructor `RfcConnection(connection_string, user_id, password, client="900", language="EN")` ### Parameters - **connection_string** (str) - Required - SAP Logon INI name or /H//S/ direct string. - **user_id** (str) - Required - SAP user. - **password** (str) - Required - SAP password (required — no SSO). - **client** (str) - Optional - SAP client. Default: "900". - **language** (str) - Optional - Logon language. Default: "EN". ``` -------------------------------- ### Top-level exports from rpa_sap/__init__.py Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/README.md Re-exports the public API from the rpa-sap package. Import these symbols from the top-level package unless stated otherwise. ```python from .core.connection import ConnectionManager from .core.session import SapSession from .core.ui_automation import ElementInteractor from .core.rfc import RfcConnection from .lib.GridView import GridView from .lib.GuiTableControl import GuiTableControl from .lib.SQ01 import SQ01 from .lib.data_extractors import GridViewExtractor, GuiTableControlExtractor from .exceptions import ( SapRpaError, SapConnectionError, SapSessionError, SapElementNotFoundError, SapTransactionError, SapProcessError, ) ``` -------------------------------- ### BasicAuthStrategy.__init__ Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/odata.md Constructor for BasicAuthStrategy, storing username and password for HTTP Basic authentication. ```APIDOC ## BasicAuthStrategy.__init__ ### Description Constructor for BasicAuthStrategy, storing username and password for HTTP Basic authentication. ### Method __init__ ### Signature `def __init__(self, username: str, password: str):` ### Parameters - **username** (str) - Required - Basic-auth user. - **password** (str) - Required - Basic-auth password. ### Returns None ``` -------------------------------- ### Basic UI Automation with ConnectionManager and ElementInteractor Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/ui-automation.md Shows how to open a new SAP session, navigate, interact with UI elements (text fields, buttons, checkboxes, comboboxes, context menus), and close the session. Requires valid SAP credentials and a running SAP Logon. ```python from rpa_sap import ConnectionManager manager = ConnectionManager() session = manager.open_new_session("S4HANA Prod", "rpa_user", "secret", client="100") i = session.interactor # Navigation and typing i.set_text("wnd[0]/tbar[0]/okcd", "MM03") i.press_enter() i.wait_until_object_exists("wnd[0]/usr/ctxtRM06E-EBELN", timeout=30) i.set_focus("wnd[0]/usr/ctxtRM06E-EBELN") # Buttons, checkboxes, comboboxes i.press_button("wnd[0]/tbar[1]/btn[8]") i.set_checkbox_state("wnd[0]/usr/chk[1,1]", True) i.select_combobox_item("wnd[0]/usr/cmbX", "KEY_01") # Context menus and raw COM access i.select_context_menu_item("wnd[0]/usr/...", "ITEM_FCODE") i.set_property("wnd[0]/usr/cntlGRID1/shellcont/shell", "selectedRows", 0) manager.close_session(session) manager.close_sap_logon() ``` -------------------------------- ### GridView class constructor Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/gridview.md Initializes a GridView instance with an active SapSession. The wrapper resolves controls through sap_session.interactor._get_object(field_id). ```python class GridView: def __init__(self, sap_session: SapSession): self.sap_session = sap_session ``` -------------------------------- ### GridViewExtractor(grid_view) Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/configuration.md Constructor for the GridViewExtractor class. Takes a GridView helper. ```APIDOC ## GridViewExtractor(grid_view) ### Description Constructor for the GridViewExtractor class. Takes a GridView helper. ### Constructor `GridViewExtractor(grid_view)` ### Parameters - **grid_view** (GridView) - Required - GridView helper for GridViewExtractor. ``` -------------------------------- ### to_local_file Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/sq01.md Exports the query result to a local file by specifying the folder path, file name, and file type. It handles the export UI flow and verifies the download was successful. ```APIDOC ## to_local_file ### Description Exports the query result to a local file by specifying the folder path, file name, and file type. It handles the export UI flow and verifies the download was successful. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `folder_path` (str) - Required - Destination folder entered into `CTXT_DIRECTORY_PATH`. - `file_name` (str) - Required - File name entered into `CTXT_FILE_NAME`. - `file_type` (str) - Optional - Mapped to a file-encoding code: `"xls"` → `"0000"`, `"csv"` → `"0004"`, anything else → `"0000"`. ### Request Example ```python to_local_file( folder_path="/path/to/folder", file_name="output", file_type="xls" ) ``` ### Response #### Success Response (200) - **Return type:** `None` #### Response Example ```python None ``` ### Error Handling - Raises built-in `Exception("Data has not been exported successfully")` if the status bar does not contain the substring `"Download"`. ``` -------------------------------- ### RfcConnection _connect method Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/rfc.md Private method that initializes the connection via SAP.Functions. Parses connection string to set ApplicationServer/SystemNumber or System, then logs on. Raises SapSessionError on any failure. ```python def _connect(self): """Initializes the connection via SAP.Functions.""" try: pythoncom.CoInitialize() self.sap_functions = win32com.client.Dispatch("SAP.Functions") rfc_conn = self.sap_functions.Connection match = re.search(r"/H/([^/]+)/S/(32\d{2})", self.connection_string) if match: ashost = match.group(1) sysnr = match.group(2)[2:] rfc_conn.ApplicationServer = ashost rfc_conn.SystemNumber = sysnr rfc_conn.UseSAPLogonIni = False else: rfc_conn.System = self.connection_string rfc_conn.UseSAPLogonIni = True rfc_conn.Client = self.client rfc_conn.User = self.user_id rfc_conn.Password = self.password rfc_conn.Language = self.language if not rfc_conn.Logon(0, True): # Silent=True raise Exception("Logon method returned False.") self.connection = rfc_conn except Exception as e: raise SapSessionError( f"Failed to establish headless RFC connection: {e}" ) from e ``` -------------------------------- ### press_enter(self, window_index: int = 0) -> None Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/ui-automation.md Presses the Enter key (VKey 0) in the specified SAP GUI window. This is a convenience method for sending the Enter key. ```APIDOC ## press_enter(self, window_index: int = 0) -> None ### Description Presses the Enter key (VKey 0) in the specified SAP GUI window. ### Method Python method ### Signature `press_enter(self, window_index: int = 0) -> None` ### Parameters - **window_index** (int) - Optional - Index of the window to send the key to. Defaults to 0. ### Return Value None ``` -------------------------------- ### SapSession(com_session, com_connection=None, sap_functions=None) Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/configuration.md Constructor for the SapSession class. Normally constructed by ConnectionManager.open_new_session or activate_session. ```APIDOC ## SapSession(com_session, com_connection=None, sap_functions=None) ### Description Constructor for the SapSession class. Normally constructed by ConnectionManager.open_new_session or activate_session. ### Constructor `SapSession(com_session, com_connection=None, sap_functions=None)` ### Parameters - **com_session** (win32com.client.CDispatch | None) - Required - COM session object. - **com_connection** (win32com.client.CDispatch | None) - Optional - Owning COM connection (needed by ConnectionManager.close_session). - **sap_functions** (win32com.client.CDispatch | None) - Optional - Optional SAP.Functions handle; stored but unused by current code. ``` -------------------------------- ### RfcConnection.__init__ Source: https://github.com/21010/rpa-sap/blob/main/_autodocs/api-reference/rfc.md Initializes a headless SAP RFC connection using the SAP.Functions COM interface. The constructor immediately opens a live RFC session and raises SapSessionError on failure. ```APIDOC ## [CONSTRUCTOR] RfcConnection.__init__ ### Description Initializes a headless SAP RFC connection using the SAP.Functions COM interface. The constructor immediately opens a live RFC session and raises SapSessionError on failure. ### Method Constructor ### Endpoint RfcConnection(connection_string, user_id, password, client="900", language="EN") ### Parameters #### Parameters - **connection_string** (str) - Required - SAP Logon entry name (e.g., "022 BPE Test") or a direct string of the form `/H//S/` (e.g., `/H/192.168.1.1/S/3200`). - **user_id** (str) - Required - SAP user name. - **password** (str) - Required - SAP password (required; no SSO mode here). - **client** (str) - Optional - SAP client. Default: "900". - **language** (str) - Optional - Logon language. Default: "EN". ### Request Example ```python RfcConnection( connection_string="022 BPE Test", user_id="myuser", password="mypassword", client="900", language="EN" ) ``` ### Response #### Success Response - **connection** (COM object) - The initialized SAP.Functions connection object. #### Error Handling - **SapSessionError** - Raised if the connection fails, including when `Logon(0, True)` returns False. ```