### OAuth authorization flow example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/client.md Example of creating an OAuth client and starting authorization with scopes. The client_id and client_secret are used to instantiate the client, and start_authorization is called with a callback URL and scopes. ```python oauth = AssinafyClient().oauth("client-id", "client-secret") start = oauth.start_authorization( "https://myapp.example/oauth/callback", ["documents:read", "documents:write", "offline_access"], ) ``` -------------------------------- ### get usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/templates.md Shows how to call client.templates.get with a template id and print the roles and default_document_tags from the returned template. ```python template = client.templates.get("template-id") print(template["roles"], template["default_document_tags"]) ``` -------------------------------- ### Installation Source: https://github.com/assinafy/python-sdk/blob/main/README.md Install the Assinafy Python SDK via pip. ```APIDOC ## Installation ```bash pip install assinafy ``` ``` -------------------------------- ### get usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhooks.md Example of calling get and checking if the result is None. ```python sub = client.webhooks.get() if sub is None: print("nenhuma assinatura") ``` -------------------------------- ### Install Assinafy SDK with pip Source: https://github.com/assinafy/python-sdk/blob/main/README.md Install the Assinafy Python SDK using pip. Requires Python 3.10+ and httpx is installed automatically. ```bash pip install assinafy ``` -------------------------------- ### create usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/tags.md Example of creating a tag with a name and color. ```python tag = client.tags.create({"name": "Contratos", "color": "ff8800"}) ``` -------------------------------- ### List accounts with client.accounts.list() Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/accounts.md Calls GET /accounts to list the authenticated user's workspaces. Returns a list of account dictionaries. The example iterates over the result and prints id, name, and roles. ```python for account in client.accounts.list(): print(account["id"], account["name"], account["roles"]) ``` -------------------------------- ### download usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signer_documents.md Example of downloading a certificated PDF artifact. ```python pdf = client.signer_documents.download("signer-id", "doc-id", "certificated") ``` -------------------------------- ### Get theme with client.accounts.theme() Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/accounts.md Calls GET /accounts/{account_id}/theme to retrieve workspace branding, e.g., {"account_name", "primary_color", "secondary_color", "logo"}. The example prints the primary_color. ```python theme = client.accounts.theme() print(theme["primary_color"]) ``` -------------------------------- ### Subclass example: MeuRecurso using BaseResource Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/base.md Shows how to create a custom resource by subclassing BaseResource. Uses _account_id to resolve the account ID and _call_list to perform a GET request and unpack the list envelope. ```python from assinafy.resources.base import BaseResource class MeuRecurso(BaseResource): def listar(self, account_id=None): acc = self._account_id(account_id) return self._call_list( "Falha ao listar", lambda: self._http.get(f"accounts/{acc}/meu-recurso"), ) ``` -------------------------------- ### Advanced HTTP client usage Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/client.md Example of retrieving the underlying httpx.Client and making a GET request to a custom path. This is for advanced usage only. ```python http = client.get_http_client() resp = http.get("whichever/path") # uso avançado ``` -------------------------------- ### Usage example for static methods Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/oauth.md Example showing how to create a code verifier, derive its challenge, and verify that state values are unique. ```python verifier = OAuthResource.create_code_verifier() challenge = OAuthResource.code_challenge(verifier) assert OAuthResource.create_state() != OAuthResource.create_state() ``` -------------------------------- ### create_api_key usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Example call to create_api_key with a password. The returned API key should be shown only once. ```python key = client.authentication.create_api_key("segredo") print(key["api_key"]) # mostre uma única vez ``` -------------------------------- ### search usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signer_documents.md Example of searching for documents with the term 'contrato'. ```python result = client.signer_documents.search("signer-id", codigo_acesso, search="contrato") ``` -------------------------------- ### sign_multiple usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signer_documents.md Example of signing multiple documents with a list of document IDs. ```python client.signer_documents.sign_multiple(["doc-1", "doc-2"], codigo_acesso) ``` -------------------------------- ### create_from_template usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example call to create a document from a template, specifying a signer with role_id, id, and verification_method, and options for name and message. ```python doc = client.documents.create_from_template( "template-id", signers=[{"role_id": "role-1", "id": "signer-id", "verification_method": "Email"}], options={"name": "NDA - João", "message": "Por favor, assine."}, ) ``` -------------------------------- ### verify_mfa usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Example call to verify_mfa with an mfa_token and a valid code. Returns a session dictionary. ```python session = client.authentication.verify_mfa(mfa_token, "123456") ``` -------------------------------- ### list and list_as_workspace usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signer_documents.md Example of listing documents with pagination and as workspace. Shows both `list` and `list_as_workspace` calls and printing the total count. ```python result = client.signer_documents.list("signer-id", codigo_acesso, {"per_page": 10}) # ou como workspace: result = client.signer_documents.list_as_workspace("signer-id") print(result["meta"]["total"]) ``` -------------------------------- ### Example usage of event extraction and object retrieval Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhook_verifier.md Shows how to extract an event from raw body, get the object, and print event type, object type, and object ID. ```python event = verifier.extract_event(raw_body) objeto = verifier.get_event_object(event) print(verifier.get_event_type(event), objeto.get("type"), objeto.get("id")) ``` -------------------------------- ### register usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhooks.md Example call to client.webhooks.register with a payload containing url and email. ```python client.webhooks.register( {"url": "https://example.com/webhooks/assinafy", "email": "ops@example.com"} ) ``` -------------------------------- ### authorization_server_metadata usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/oauth.md Example of calling authorization_server_metadata and printing the scopes_supported and code_challenge_methods_supported fields. ```python meta = oauth.authorization_server_metadata() print(meta["scopes_supported"], meta["code_challenge_methods_supported"]) ``` -------------------------------- ### verify usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhook_verifier.md Example of calling verify to check a webhook signature and returning 401 on failure. ```python if not verifier.verify(body, header_signature): return 401 ``` -------------------------------- ### current method usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signer_documents.md Example of calling `client.signer_documents.current` with a signer ID and access code, then printing the document status. ```python doc = client.signer_documents.current("signer-id", codigo_acesso) print(doc["status"]) ``` -------------------------------- ### protected_resource_metadata usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/oauth.md Example of calling protected_resource_metadata and printing the authorization_servers field. ```python meta = oauth.protected_resource_metadata() print(meta["authorization_servers"]) ``` -------------------------------- ### send_token usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example call to send_token with a recipient email. ```python result = client.documents.send_token("doc-id", recipient="signer@example.com") ``` -------------------------------- ### Check and start identity verification Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Checks if identity verification can be started, then starts a session with consent=True and prints the session URL. ```python state = client.signers.identity_verification(codigo_acesso) if state["can_start"]: session = client.signers.start_identity_verification(codigo_acesso, consent=True) print(session["url"]) ``` -------------------------------- ### delete usage example with force Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/tags.md Example of deleting a tag with force=True. ```python client.tags.delete("tag-id", force=True) ``` -------------------------------- ### update usage examples Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/tags.md Examples of updating a tag's name and clearing its color. ```python client.tags.update("tag-id", {"name": "Contratos de Venda"}) client.tags.update("tag-id", {"color": None}) # limpa a cor ``` -------------------------------- ### Context manager usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/client.md Example of using AssinafyClient as a context manager. Connections are closed when exiting the with block. ```python with AssinafyClient(api_key="k_xxx") as client: pass # conexões fechadas ao sair ``` -------------------------------- ### estimate_cost usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/assignments.md Example call to estimate_cost with a virtual method and a signer using WhatsApp verification and notification. Prints the total credits and whether sufficient resources exist. ```python est = client.assignments.estimate_cost( "doc-id", {"method": "virtual", "signers": [{"verification_method": "Whatsapp", "notification_methods": ["Whatsapp"]}]}, ) print(est["total_credits"], est["has_sufficient_resources"]) ``` -------------------------------- ### get method signature Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/templates.md Defines the get method that sends GET /accounts/{account_id}/templates/{template_id}. Returns a single template dict. ```python def get(self, template_id: str, account_id: str | None = None) -> dict[str, Any]: ``` -------------------------------- ### decline_multiple usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signer_documents.md Example of declining a document with a reason. ```python client.signer_documents.decline_multiple(["doc-1"], "Termos desfavoráveis.", codigo_acesso) ``` -------------------------------- ### change_password usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Example of calling change_password with an email, current password, and new password. ```python client.authentication.change_password("usuario@example.com", "antiga", "nova") ``` -------------------------------- ### get_event_type usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhook_verifier.md Example of retrieving the event type and comparing it to 'document_ready'. ```python event_type = verifier.get_event_type(event) if event_type == "document_ready": ... ``` -------------------------------- ### get_api_key usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Example of calling get_api_key and checking for None to handle the case where no API key has been generated. ```python key = client.authentication.get_api_key() if key is None: print("Nenhuma chave ainda") ``` -------------------------------- ### list_dispatches usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhooks.md Example of calling list_dispatches with event and delivered filters, then printing the total from meta. ```python result = client.webhooks.list_dispatches({"event": "document_ready", "delivered": True}) print(result["meta"]["total"]) ``` -------------------------------- ### verify usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example of calling verify with a signature hash. The response includes is_valid and message fields. ```python result = client.documents.verify("0000...") print(result["is_valid"], result["message"]) ``` -------------------------------- ### get_self usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Example of calling get_self and accessing the added fields. ```python self_view = client.signers.get_self(codigo_acesso) print(self_view["has_signature"], self_view["verification_method"]) ``` -------------------------------- ### list_event_types usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhooks.md Example of iterating over event types and printing their IDs. ```python for event_type in client.webhooks.list_event_types(): print(event_type["id"]) ``` -------------------------------- ### estimate_cost_from_template usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example of calling estimate_cost_from_template with a template ID and a signer list. The response contains total_credits and has_sufficient_resources. ```python est = client.documents.estimate_cost_from_template( "template-id", signers=[{"role_id": "role-1"}] ) print(est["total_credits"], est["has_sufficient_resources"]) ``` -------------------------------- ### Account management: list, create, update, get, theme, stats, logo, delete Source: https://github.com/assinafy/python-sdk/blob/main/README.md Shows the full account lifecycle: list accounts, create a workspace, update notification sender type, get account, update name, fetch theme, get monthly or daily stats, upload/download/delete logo, and delete the account. The delete() method makes force a keyword-only argument to avoid positional confusion; use force=True only to intentionally cancel an active paid subscription. ```python accounts = client.accounts.list() nova_conta = client.accounts.create("Workspace de Exemplo") nova_id = nova_conta["id"] nova_conta = client.accounts.update({"notification_sender_type": "Account"}, nova_id) nova_conta = client.accounts.get(nova_id) nova_conta = client.accounts.update({"name": "Workspace Atualizado"}, nova_id) theme = client.accounts.theme(nova_id) stats = client.accounts.stats("monthly", account_id=nova_id) stats_diarias = client.accounts.stats("daily", "2026-08", account_id=nova_id) client.accounts.upload_logo({"file_path": "./logo.png"}, nova_id) logo_bytes = client.accounts.download_logo(nova_id) client.accounts.delete_logo(nova_id) # Apague apenas o workspace descartável criado acima. client.accounts.delete(nova_id) ``` -------------------------------- ### find_by_email usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Example of calling find_by_email and checking if a signer was found. ```python signer = client.signers.find_by_email("joao@example.com") if signer is None: print("não encontrado") ``` -------------------------------- ### refresh usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/oauth.md Shows how to call refresh with the current refresh token and emphasizes persisting the new refresh token immediately. ```python tokens = oauth.refresh(tokens["refresh_token"]) # persista tokens["refresh_token"] imediatamente ``` -------------------------------- ### list usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/tags.md Example of listing tags with a search filter. Iterates over the returned data and prints tag id, name, and color. ```python result = client.tags.list({"search": "Contratos"}) for tag in result["data"]: print(tag["id"], tag["name"], tag["color"]) ``` -------------------------------- ### start_authorization usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/oauth.md Shows how to call start_authorization with a redirect URI and scopes, then store the returned transaction and redirect the browser to the authorization URL. ```python oauth = client.oauth("client-id", "client-secret") transaction = oauth.start_authorization( "https://myapp.example/oauth/callback", ["documents:read", "documents:write", "offline_access"], ) # guarde transaction na sessão e redirecione o navegador: # redirect(transaction["authorization_url"]) ``` -------------------------------- ### link_social_login usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Example call to link_social_login with provider 'google' and a token. The method returns None. ```python client.authentication.link_social_login("google", "ya29.a0Af...") ``` -------------------------------- ### Get account with client.accounts.get() Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/accounts.md Calls GET /accounts/{account_id} to retrieve a workspace, using the default account_id or an explicit one. Returns the account payload. ```python account = client.accounts.get() ``` -------------------------------- ### review_identity_verification usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/assignments.md Example call to review an identity verification with decision 'Approved' and a note. The response is a dictionary with the full identity_verification shape. Returns 400 for invalid decision or state, 404 when no verification exists. ```python result = client.assignments.review_identity_verification( "doc-id", "asg-id", "signer-id", "Approved", note="Identidade confirmada pelo revisor" ) print(result["status"]) ``` -------------------------------- ### login usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Shows how to call login and check for mfa_token to handle 2FA. Prints the access token when 2FA is not enabled. ```python session = client.authentication.login("usuario@example.com", "senha") if "mfa_token" in session: print("Complete com verify_mfa") print(session["access_token"]) # quando sem 2FA ``` -------------------------------- ### Get userinfo claims Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/oauth.md Example call to retrieve OIDC claims for an access token and print the subject and optional name claim. ```python claims = oauth.userinfo(tokens["access_token"]) print(claims["sub"], claims.get("name")) ``` -------------------------------- ### Client Initialization Source: https://github.com/assinafy/python-sdk/blob/main/README.md Create an AssinafyClient instance with API key or token authentication. ```APIDOC ## Client Initialization ### Description Create a client instance for interacting with the Assinafy API. ### Parameters - **api_key** (str) - Optional - API key sent as `X-Api-Key`. - **token** (str) - Optional - Access token sent as `Authorization: Bearer `. - **account_id** (str) - Optional - Default account/workspace ID. - **base_url** (str) - Optional - Base URL of the API. Default: `https://api.assinafy.com.br/v1`. - **webhook_secret** (str) - Optional - Webhook signing secret (`whsec_...`). - **timeout** (float) - Optional - Request timeout in seconds. Default: `30.0`. - **logger** (object) - Optional - Logger object with `debug/info/warning/error` methods. ### Example ```python client = AssinafyClient(api_key="k_xxx", account_id="acc_xxx") client = AssinafyClient(token="jwt_xxx", account_id="acc_xxx") ``` ``` -------------------------------- ### start_authorization() Source: https://github.com/assinafy/python-sdk/blob/main/README.md Generates a new PKCE verifier and state (and nonce if openid is requested) and returns the authorization URL and transaction data. Does not make an HTTP request. ```APIDOC ## start_authorization() ### Description Generates a new PKCE verifier and state (and nonce if openid is requested) and returns the authorization URL and transaction data. Does not make an HTTP request. ### Method Function call ### Parameters - **redirect_uri** (string) - Required - The callback URL where the user will be redirected after authorization. - **scopes** (list of strings) - Required - List of OAuth scopes to request, e.g., ["documents:read", "documents:write", "offline_access"]. ### Returns A dictionary containing: - **authorization_url** (string) - The full authorization URL to redirect the user to. - **state** (string) - Random state value for CSRF protection. - **code_verifier** (string) - Random PKCE code verifier. - **code_challenge** (string) - SHA256 hash of the verifier, base64url encoded. - **redirect_uri** (string) - The redirect URI used. - **issuer** (string) - The issuer URL. - **resource** (string) - The resource URL. ### Example ```python start = oauth.start_authorization( "https://meuapp.example.com/oauth/callback", ["documents:read", "documents:write", "offline_access"], ) session["assinafy_oauth"] = start return redirect(start["authorization_url"]) ``` ``` -------------------------------- ### update usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Example of calling the update method to change a signer's full name. ```python signer = client.signers.update("signer-id", {"full_name": "Johnny Doe"}) ``` -------------------------------- ### Webhook endpoint usage examples Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhooks.md Examples of updating, deleting, and deleting by URL using the client. update_endpoint only updates provided fields; delete_endpoint_by_url returns 404 if no endpoint uses the URL. ```python client.webhooks.update_endpoint("endpoint-id", {"events": ["document_ready"], "is_active": False}) client.webhooks.delete_endpoint("endpoint-id") client.webhooks.delete_endpoint_by_url("https://example.com/webhooks/assinafy") ``` -------------------------------- ### download_identity_verification_image usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/assignments.md Example call to download an identity verification image for the 'face' name. The response is bytes of the image. The API sends Cache-Control: no-store, so keep evidence out of caches and logs. Returns 404 when the review is already decided or images are absent. ```python img = client.assignments.download_identity_verification_image( "doc-id", "asg-id", "signer-id", "face" ) ``` -------------------------------- ### Create account with client.accounts.create() Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/accounts.md Calls POST /accounts to create a workspace. Sends name and optionally notification_sender_type ("User" or "Account"). Returns the full account payload. ```python account = client.accounts.create("Acme Inc.", notification_sender_type="Account") ``` -------------------------------- ### get_for_signer usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/assignments.md Example of calling get_for_signer with a signer access code and printing the status and assignment ID from the returned view. ```python view = client.assignments.get_for_signer(codigo_acesso) print(view["status"], view["assignment"]["id"]) ``` -------------------------------- ### social_login usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Example call to social_login with provider 'google' and a token. The has_accepted_terms parameter is set to True. Returns a session dictionary. ```python session = client.authentication.social_login("google", "ya29.a0Af...", has_accepted_terms=True) ``` -------------------------------- ### sign usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/assignments.md Example of calling sign with a document ID, assignment ID, a list of entry objects, and a signer access code. ```python client.assignments.sign( "doc-id", "asg-id", [{"itemId": "615605f8...", "fieldId": "61521202...", "pageId": "615213ed...", "value": "João Silva"}], codigo_acesso, ) ``` -------------------------------- ### Initialize AssinafyClient with API key and account ID Source: https://github.com/assinafy/python-sdk/blob/main/README.md Creates an AssinafyClient using environment variables ASSINAFY_API_KEY and ASSINAFY_ACCOUNT_ID. Required before any API calls. ```python import os from assinafy import AssinafyClient client = AssinafyClient( api_key=os.environ["ASSINAFY_API_KEY"], account_id=os.environ["ASSINAFY_ACCOUNT_ID"], ) ``` -------------------------------- ### create_endpoint usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhooks.md Creates a webhook endpoint with the required url, email, and events, plus optional name, is_active, and signing_enabled. ```python endpoint = client.webhooks.create_endpoint( { "url": "https://example.com/webhooks/assinafy", "email": "ops@example.com", "events": ["document_ready", "signer_signed_document"], "name": "ERP", "is_active": True, "signing_enabled": True, } ) ``` -------------------------------- ### Custom logger example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/types.md Example of a custom logger class that satisfies the Logger protocol, and its usage with AssinafyClient. The logger methods print the message with a level prefix. ```python class MeuLogger: def debug(self, message, context=None): print("DEBUG", message) def info(self, message, context=None): print("INFO", message) def warning(self, message, context=None): print("WARN", message) def error(self, message, context=None): print("ERR", message) client = AssinafyClient(api_key="k_xxx", logger=MeuLogger()) ``` -------------------------------- ### identity_verification and start_identity_verification method signatures Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Method signatures for checking identity verification state and starting a verification session. The first method queries the current state, the second requires consent=True to start a session. ```python def identity_verification(self, signer_access_code: str) -> dict[str, Any]: def start_identity_verification( self, signer_access_code: str, *, consent: bool ) -> dict[str, Any]: ``` -------------------------------- ### Wait for document readiness Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example of waiting for a document to be ready with a custom timeout and poll interval. ```python doc = client.documents.wait_until_ready("doc-id", timeout=60.0, poll_interval=2.0) ``` -------------------------------- ### get Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/accounts.md Retrieves a workspace, either the default account or a specified one. Returns the full account payload. ```APIDOC ## GET /accounts/{account_id} ### Description Retrieves a workspace, either the default account or a specified one. Returns the full account payload. ### Method GET ### Endpoint /accounts/{account_id} ### Parameters #### Path Parameters - **account_id** (string) - Optional - The account ID. If not provided, the client's default account is used. ### Response #### Success Response (200) - **account** (object) - The full account payload with fields: resource, id, name, primary_color, secondary_color, notification_sender_type, roles, is_delete_allowed, created_at. #### Response Example ```json { "resource": "account", "id": "string", "name": "string", "primary_color": "string", "secondary_color": "string", "notification_sender_type": "string", "roles": ["string"], "is_delete_allowed": true, "created_at": "string" } ``` ### Usage Example ```python account = client.accounts.get() ``` ``` -------------------------------- ### Upload and download signature Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Example calls to `upload_signature` and `download_signature`. Uploads raw PNG bytes with `reuse=True`, then downloads the signature image. ```python client.signers.upload_signature(codigo_acesso, png_bytes, reuse=True) image = client.signers.download_signature(codigo_acesso, "signature") ``` -------------------------------- ### Call verify_code Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Example call to `verify_code` with a signer access code and the verification code. ```python client.signers.verify_code(codigo_acesso, "123456") ``` -------------------------------- ### inactivate usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhooks.md Example of calling inactivate to deactivate the webhook. ```python client.webhooks.inactivate() ``` -------------------------------- ### start_authorization Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/oauth.md Starts an OAuth authorization connection by generating PKCE material and building the authorization URL. This is a pure string construction method with no HTTP requests. Call once per attempt; a new code_verifier/state is generated each time. Persist the entire returned value in the server's authenticated session and redirect the browser to authorization_url with full page navigation (never AJAX). ```APIDOC ## start_authorization ### Description Starts an OAuth authorization connection by generating PKCE material and building the authorization URL. This is a pure string construction method with no HTTP requests. Call once per attempt; a new code_verifier/state is generated each time. Persist the entire returned value in the server's authenticated session and redirect the browser to authorization_url with full page navigation (never AJAX). ### Method Function call (Python SDK) ### Signature ```python def start_authorization( self, redirect_uri: str, scopes: list[OAuthScope] | list[str], *, issuer: str | None = None, authorization_endpoint: str | None = None, state: str | None = None, nonce: str | None = None, code_verifier: str | None = None, resource: str | None = None, ) -> dict[str, Any]: ``` ### Parameters - **redirect_uri** (str) - Required - One of the registered URIs, character by character. Must be https:// without fragment; http://localhost is not accepted - use HTTPS tunnel. - **scopes** (list[OAuthScope] | list[str]) - Required - Requested permissions; see OAuthScope in types.md. Unlisted scopes are not rejected locally (the server may publish new ones). - **issuer** (str | None) - Optional - Default: DEFAULT_ISSUER - Origin of the authorization server; pass authorization_servers[0] from protected_resource_metadata to follow discovery. - **authorization_endpoint** (str | None) - Optional - Default: {issuer}/oauth/authorize - Overrides the endpoint, for configuration from authorization_server_metadata. - **state** (str | None) - Optional - Default: generated - Your own state per attempt. - **nonce** (str | None) - Optional - Default: generated (only with openid) - Your own OIDC nonce; only used with the openid scope (the only case that generates id_token). - **code_verifier** (str | None) - Optional - Default: generated - Your own RFC 7636 verifier. - **resource** (str | None) - Optional - Default: API origin - RFC 8707 resource indicator; default is what the token endpoint expects. ### Return Value Returns a transaction dictionary: {"authorization_url", "state", "code_verifier", "code_challenge", "nonce"?, "redirect_uri", "issuer", "resource"} - to be stored and returned to handle_callback and exchange_code. ### Exceptions - **ValidationError** - Thrown when: redirect URI is unusable, scopes list is empty, scope is blank or contains spaces (scope is space-delimited in the wire; an embedded space would silently request two permissions), or code_verifier is malformed. ### Example ```python oauth = client.oauth("client-id", "client-secret") transaction = oauth.start_authorization( "https://myapp.example/oauth/callback", ["documents:read", "documents:write", "offline_access"], ) # guarde transaction na sessão e redirecione o navegador: # redirect(transaction["authorization_url"]) ``` ``` -------------------------------- ### Template Operations: List, Get, Create Document, Estimate Cost Source: https://github.com/assinafy/python-sdk/blob/main/README.md Lists templates, retrieves a template by ID, creates a document from a template, and estimates cost. The published OpenAPI exposes only `list`; `get` is kept because the route is deployed and responds on the live API, and the published schema text describes a single-template response that adds `default_document_tags`. ```python templates = client.templates.list({"search": "NDA", "per_page": 20}) template = client.templates.get(template_id) client.documents.create_from_template( template_id, [{"role_id": "role-id", "id": signer_id, "verification_method": "Email"}], {"name": "NDA - João Silva", "message": "Por favor, assine."}, ) client.documents.estimate_cost_from_template( template_id, [{"role_id": "role-id", "verification_method": "Email"}], ) ``` -------------------------------- ### Fetch a document by ID Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example of fetching a document using client.documents.get() and printing its status and assignment. ```python doc = client.documents.get("doc-id") print(doc["status"], doc["assignment"]) ``` -------------------------------- ### Rename a document Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example of renaming a document using client.documents.rename(). ```python client.documents.rename("doc-id", "Acordo de serviços.pdf") ``` -------------------------------- ### handle_callback usage example with error handling Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/oauth.md Example of calling handle_callback with the framework query and the stored transaction, catching ValidationError for invalid callbacks (CSRF/issuer mismatch) and ApiError for authorization server errors, such as access_denied. ```python from assinafy import ApiError, ValidationError try: code = oauth.handle_callback(framework_query, session["oauth_transaction"]) except ValidationError as err: print("callback inválido:", err) # CSRF/issuer errado except ApiError as err: if str(err) == "access_denied": print("usuário recusou:", err.response_data.get("error_description")) ``` -------------------------------- ### Tag management usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example calls to append_tags, replace_tags, and detach_tag. append_tags adds tags without removing existing ones, replace_tags with an empty list detaches all tags, and detach_tag returns a dictionary with a 'detached' key. ```python client.documents.append_tags("doc-id", ["tag-id-1"]) client.documents.replace_tags("doc-id", []) result = client.documents.detach_tag("doc-id", "tag-id-1") print(result["detached"]) ``` -------------------------------- ### list_endpoints usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhooks.md Iterates over the endpoints returned by list_endpoints and prints each endpoint's id, url, and signing_enabled flag. ```python for endpoint in client.webhooks.list_endpoints(): print(endpoint["id"], endpoint["url"], endpoint["signing_enabled"]) ``` -------------------------------- ### Start OAuth authorization with start_authorization() Source: https://github.com/assinafy/python-sdk/blob/main/README.md Generates a new PKCE verifier and state (and nonce if openid is requested) and returns the authorization URL and transaction data. Does not make an HTTP request. Call once per connection attempt and store the result in the user's authenticated session, not in cookies or URL. If client_id or redirect_uri are wrong, the user is not redirected back; the authorization server shows the error on its own page. ```python start = oauth.start_authorization( "https://meuapp.example.com/oauth/callback", ["documents:read", "documents:write", "offline_access"], ) session["assinafy_oauth"] = start # a sessão de servidor do usuário return redirect(start["authorization_url"]) # navegação de página completa, não AJAX ``` -------------------------------- ### Comandos de desenvolvimento (instalação, testes, mypy, ruff) Source: https://github.com/assinafy/python-sdk/blob/main/README.md Comandos para configurar o ambiente de desenvolvimento e executar a suíte de qualidade: instalação com extras de desenvolvimento, testes com cobertura mínima de 90%, verificação de tipos com mypy e linting/format com ruff. ```bash python -m pip install -e ".[dev]" python -m pytest --cov=assinafy --cov-branch --cov-fail-under=90 --cov-report=term-missing python -m mypy src scripts/live_smoke.py python -m ruff check src tests scripts python -m ruff format --check src tests scripts ``` -------------------------------- ### delete usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example call to delete a document by its ID. ```python client.documents.delete("doc-id") ``` -------------------------------- ### Get stats with client.accounts.stats() Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/accounts.md Calls GET /accounts/{account_id}/stats to retrieve document KPI rows. Supports granularity=monthly (default) or granularity=daily&month=YYYY-MM; daily queries require month. Raises ValidationError for invalid granularity, malformed month, or missing month in daily mode. ```python rows = client.accounts.stats("daily", "2026-06") for row in rows: print(row["period"], row["documents_uploaded"]) ``` -------------------------------- ### get method signature Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Signature for the get method that retrieves a document by ID. ```python def get(self, document_id: str) -> dict[str, Any]: ``` -------------------------------- ### reset_password usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Shows how to call the reset_password method on the client's authentication resource with an email, new password, and a token. ```python client.authentication.reset_password("usuario@example.com", "nova", token="b3ac64d6c55...") ``` -------------------------------- ### Accept terms example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Calls accept_terms with the signer access code to register terms acceptance. ```python client.signers.accept_terms(codigo_acesso) ``` -------------------------------- ### List documents with filters Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example of listing documents with pagination and status filter. The result contains metadata and data array. ```python result = client.documents.list({"per_page": 50, "status": "pending_signature"}) print(result["meta"], len(result["data"])) ``` -------------------------------- ### delete validation error example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/tags.md Example of catching a ValidationError when force is not a boolean. ```python from assinafy import ValidationError try: client.tags.delete("tag-id", force="sim") except ValidationError as err: print("force precisa ser booleano") ``` -------------------------------- ### Environments Source: https://github.com/assinafy/python-sdk/blob/main/README.md The SDK supports two environments: Production and Sandbox. The sandbox allows testing with disposable resources and simulated WhatsApp messages. ```APIDOC ## Environments ### Description O SDK suporta dois ambientes: Produção e Sandbox. O sandbox permite testar a integração com recursos descartáveis. Mensagens de WhatsApp são simuladas nesse ambiente. O registro e o consentimento OAuth usam o servidor de autorização de produção; os endpoints de token e os metadados também existem no sandbox. A assinatura A1/A3 exige um certificado ICP-Brasil real no dispositivo do signatário e o fluxo de assinatura hospedado pela Assinafy. ### Production `https://api.assinafy.com.br/v1` ### Sandbox `https://sandbox.assinafy.com.br/v1` ``` -------------------------------- ### delete usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/signers.md Example of calling the delete method to remove a signer. ```python client.signers.delete("signer-id") ``` -------------------------------- ### public_info usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Example call to public_info using a document ID. ```python info = client.documents.public_info("doc-id") ``` -------------------------------- ### Create virtual assignment example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/assignments.md Creates a virtual signing assignment with a message and signers, then prints the signing URLs from the response. The `method` is set to `virtual`. ```python assignment = client.assignments.create( "doc-id", { "method": "virtual", "message": "Por favor, assine", "signers": [ {"id": "signer-id", "verification_method": "Email", "notification_methods": ["Email"], "step": 1} ], }, ) print(assignment["signing_urls"]) ``` -------------------------------- ### list usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/templates.md Shows how to call client.templates.list with search and per_page parameters, then iterate over the returned data to print template id, name, and status. ```python result = client.templates.list({"search": "nda", "per_page": 10}) for template in result["data"]: print(template["id"], template["name"], template["status"]) ``` -------------------------------- ### start_authorization() return value Source: https://github.com/assinafy/python-sdk/blob/main/README.md Example JSON object returned by start_authorization(). Contains authorization_url, state, code_verifier, code_challenge, redirect_uri, issuer, and resource. The code_challenge is the SHA256 of the verifier in base64url. ```json { "authorization_url": "https://auth.assinafy.com.br/oauth/authorize?response_type=code&...", "state": "", "code_verifier": "", "code_challenge": "", "redirect_uri": "https://meuapp.example.com/oauth/callback", "issuer": "https://auth.assinafy.com.br", "resource": "https://api.assinafy.com.br", } ``` -------------------------------- ### start_totp_enrollment - Start TOTP enrollment Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Initiates TOTP enrollment for an authenticator app. Creates an unconfirmed method and returns its 'secret' and 'provisioning_uri' (for QR code rendering). The secret is only returned in this call. 2FA remains off until confirm_totp_enrollment succeeds. ```python def start_totp_enrollment(self, label: str | None = None) -> dict[str, Any]: ``` ```python enroll = client.authentication.start_totp_enrollment(label="Meu celular") print(enroll["secret"], enroll["provisioning_uri"]) # mostrar QR code ao usuário ``` -------------------------------- ### get Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/fields.md Retrieves a single field definition via GET /accounts/{account_id}/fields/{field_id}. ```APIDOC ## GET /accounts/{account_id}/fields/{field_id} ### Description Retrieves a single field definition by its ID. ### Method GET ### Endpoint /accounts/{account_id}/fields/{field_id} ### Parameters #### Path Parameters - **account_id** (string) - Optional - The account ID. If not provided, the client's default account is used. - **field_id** (string) - Required - The ID of the field to retrieve. ### Response #### Success Response (200) Returns the field definition object. #### Response Example ```json { "id": "field-id", "type": "text", "name": "CPF" } ``` ``` -------------------------------- ### request_password_reset usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Example of calling request_password_reset with an email to send a password reset token. ```python client.authentication.request_password_reset("usuario@example.com") ``` -------------------------------- ### Teste de fumaça ao vivo (fluxo de escrita descartável) Source: https://github.com/assinafy/python-sdk/blob/main/README.md Executa o teste de fumaça ao vivo com fluxo de escrita descartável, incluindo envio de notificações de teste e mutações de conta e preferências de usuário. Requer as variáveis de ambiente ASSINAFY_API_KEY, ASSINAFY_ACCOUNT_ID, ASSINAFY_BASE_URL e ASSINAFY_TEST_EMAILS. ```bash ASSINAFY_API_KEY=... \ ASSINAFY_ACCOUNT_ID=... \ ASSINAFY_BASE_URL=https://sandbox.assinafy.com.br/v1 \ ASSINAFY_TEST_EMAILS=primeiro@example.com,segundo@example.com \ ASSINAFY_SEND_TEST_NOTIFICATIONS=1 \ ASSINAFY_TEST_ACCOUNT_LIFECYCLE=1 \ ASSINAFY_TEST_USER_PREFERENCES=1 \ python scripts/live_smoke.py ``` -------------------------------- ### Download a document and save to file Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/documents.md Downloads a document with artifact_name 'certificated' and writes the raw bytes to a local file 'assinado.pdf'. ```python pdf = client.documents.download("doc-id", "certificated") with open("assinado.pdf", "wb") as f: f.write(pdf) ``` -------------------------------- ### extract_event usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/webhook_verifier.md Example of extracting the event from the raw body and returning 400 when it is not a JSON object. ```python event = verifier.extract_event(raw_body) if event is None: return 400 # corpo não é JSON objet ``` -------------------------------- ### AssinafyClient.__init__ Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/client.md Constructor for the AssinafyClient class. Validates all arguments, creates an httpx.Client with appropriate authentication headers, forces TLS 1.2+, and installs a request hook. Raises ValidationError for invalid arguments. ```APIDOC ## AssinafyClient.__init__ ### Description Constructor for the AssinafyClient class. Validates all arguments, creates an httpx.Client with appropriate authentication headers, forces TLS 1.2+, and installs a request hook. Raises ValidationError for invalid arguments. ### Method Constructor ### Signature ```python def __init__( self, api_key: str | None = None, token: str | None = None, account_id: str | None = None, base_url: str | None = None, webhook_secret: str | None = None, timeout: float = 30.0, logger: Logger | None = None, ) -> None: ``` ### Parameters - **api_key** (str | None) - Optional - API key sent in the `X-Api-Key` header. Preferred over `token`. - **token** (str | None) - Optional - Access token sent as `Authorization: Bearer ...`. Used only when `api_key` is not provided. - **account_id** (str | None) - Optional - Workspace ID used as default in account-scoped methods (e.g., `documents.list`). Can be overridden per call. - **base_url** (str | None) - Optional - Base URL of the API. Default: `https://api.assinafy.com.br/v1`. Sandbox: `https://sandbox.assinafy.com.br/v1`. Must contain only scheme, host, port, and path; embedded credentials (`user:pass@`), query string, and fragment are rejected. `http://` is rejected for all non-loopback hosts. - **webhook_secret** (str | None) - Optional - Webhook signing secret (`whsec_...`) used by `client.webhook_verifier`. - **timeout** (float) - Optional - Per-request timeout in seconds. Must be a positive finite number. Default: `30.0`. - **logger** (Logger | None) - Optional - Logger object with `debug`/`info`/`warning`/`error` methods. Default: no-op logger. The stdlib `logging.Logger` does not work directly (does not accept `(message, context)`); wrap it in an adapter. ### Construction Effects - Validates all arguments before creating any connection; failures raise `ValidationError` (`src/assinafy/client.py:100-135`). - Creates the `httpx.Client` with `User-Agent: Assinafy-Python-SDK/v` and `Accept: */*`, plus `X-Api-Key` or `Authorization: Bearer ...` depending on the provided credential (`client.py:139-155`). - Forces TLS 1.2+ (`ssl.TLSVersion.TLSv1_2`) over the default httpx context (certifi, `SSL_CERT_FILE`/`SSL_CERT_DIR`). - Installs the `request` event hook `_prepare_request`, which applies the SDK identity and protects client credentials (see [endpoints.md](../endpoints.md)). ### Exceptions - **ValidationError** - Raised for invalid arguments. ### Example ```python from assinafy import AssinafyClient # API key (preferred) client = AssinafyClient(api_key="k_xxx", account_id="acc_xxx") # User token client = AssinafyClient(token="jwt_xxx", account_id="acc_xxx") # Public client (no credentials), only public/access-code endpoints public_client = AssinafyClient() ``` ```python from assinafy import AssinafyClient, ValidationError try: client = AssinafyClient( base_url="http://api.insegura.example", # rejected: http outside loopback ) except ValidationError as err: print("Invalid configuration:", err) # Usage as context manager with AssinafyClient(api_key="k_xxx", account_id="acc_xxx") as client: doc = client.documents.get("doc-id") ``` ``` -------------------------------- ### delete_api_key usage example Source: https://github.com/assinafy/python-sdk/blob/main/_autodocs/api-reference/authentication.md Example of calling delete_api_key to revoke the current user's API key. ```python client.authentication.delete_api_key() ``` -------------------------------- ### Authenticate with API key or token Source: https://github.com/assinafy/python-sdk/blob/main/README.md Create an AssinafyClient using either an API key (sent as X-Api-Key) or a user token (sent as Authorization: Bearer). If both are provided, the API key takes precedence. ```python client = AssinafyClient(api_key="k_xxx", account_id="acc_xxx") client = AssinafyClient(token="jwt_xxx", account_id="acc_xxx") ```