{"id":18369605,"url":"https://github.com/unstructured-io/unstructured-python-client","last_synced_at":"2025-05-15T15:06:39.917Z","repository":{"id":195649550,"uuid":"689850105","full_name":"Unstructured-IO/unstructured-python-client","owner":"Unstructured-IO","description":"A Python client for the Unstructured Platform API","archived":false,"fork":false,"pushed_at":"2025-05-11T00:12:32.000Z","size":7379,"stargazers_count":101,"open_issues_count":17,"forks_count":17,"subscribers_count":20,"default_branch":"main","last_synced_at":"2025-05-11T01:20:10.788Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Unstructured-IO.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-09-11T03:20:22.000Z","updated_at":"2025-05-09T16:18:28.000Z","dependencies_parsed_at":"2023-11-28T20:28:08.429Z","dependency_job_id":"bee41e84-625d-4472-b035-89dca19cff93","html_url":"https://github.com/Unstructured-IO/unstructured-python-client","commit_stats":{"total_commits":300,"total_committers":22,"mean_commits":"13.636363636363637","dds":0.6133333333333333,"last_synced_commit":"b3ab9b9f82042baaab476a627f1272642a209df7"},"previous_names":["unstructured-io/unstructured-python-client","unstructured-io/unstructured-client"],"tags_count":85,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Unstructured-IO%2Funstructured-python-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Unstructured-IO%2Funstructured-python-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Unstructured-IO%2Funstructured-python-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Unstructured-IO%2Funstructured-python-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Unstructured-IO","download_url":"https://codeload.github.com/Unstructured-IO/unstructured-python-client/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254198373,"owners_count":22030954,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-05T23:29:55.754Z","updated_at":"2025-05-15T15:06:39.905Z","avatar_url":"https://github.com/Unstructured-IO.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch3 align=\"center\"\u003e\n  \u003cimg\n    src=\"https://raw.githubusercontent.com/Unstructured-IO/unstructured/main/img/unstructured_logo.png\"\n    height=\"200\"\n  \u003e\n\u003c/h3\u003e\n\n\u003cdiv align=\"center\"\u003e\n    \u003ca href=\"https://speakeasyapi.dev/\"\u003e\u003cimg src=\"https://custom-icon-badges.demolab.com/badge/-Built%20By%20Speakeasy-212015?style=for-the-badge\u0026logoColor=FBE331\u0026logo=speakeasy\u0026labelColor=545454\" /\u003e\u003c/a\u003e\n\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n\n\u003c/div\u003e\n\n\u003ch2 align=\"center\"\u003e\n  \u003cp\u003ePython SDK for the Unstructured API\u003c/p\u003e\n\u003c/h2\u003e\n\nThis is a HTTP client for the [Unstructured Platform API](https://docs.unstructured.io/platform-api/overview). You can sign up [here](https://unstructured.io/developers) and process 1000 free pages per day for 14 days.\n\nPlease refer to the our documentation for a full guide on integrating the [Workflow Endpoint](https://docs.unstructured.io/platform-api/api/overview) and [Partition Endpoint](https://docs.unstructured.io/platform-api/partition-api/sdk-python) into your Python code.\n\n\u003c!-- Start Summary [summary] --\u003e\n## Summary\n\n\n\u003c!-- End Summary [summary] --\u003e\n\n\u003c!-- Start Table of Contents [toc] --\u003e\n## Table of Contents\n\u003c!-- $toc-max-depth=2 --\u003e\n  * [SDK Installation](#sdk-installation)\n  * [Retries](#retries)\n  * [Error Handling](#error-handling)\n  * [Custom HTTP Client](#custom-http-client)\n  * [IDE Support](#ide-support)\n  * [SDK Example Usage](#sdk-example-usage)\n  * [Configuration](#configuration)\n  * [File uploads](#file-uploads)\n  * [Resource Management](#resource-management)\n  * [Debugging](#debugging)\n\n\u003c!-- End Table of Contents [toc] --\u003e\n\n\u003c!-- Start SDK Installation [installation] --\u003e\n## SDK Installation\n\n\u003e [!NOTE]\n\u003e **Python version upgrade policy**\n\u003e\n\u003e Once a Python version reaches its [official end of life date](https://devguide.python.org/versions/), a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.\n\nThe SDK can be installed with either *pip* or *poetry* package managers.\n\n### PIP\n\n*PIP* is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.\n\n```bash\npip install unstructured-client\n```\n\n### Poetry\n\n*Poetry* is a modern tool that simplifies dependency management and package publishing by using a single `pyproject.toml` file to handle project metadata and dependencies.\n\n```bash\npoetry add unstructured-client\n```\n\n### Shell and script usage with `uv`\n\nYou can use this SDK in a Python shell with [uv](https://docs.astral.sh/uv/) and the `uvx` command that comes with it like so:\n\n```shell\nuvx --from unstructured-client python\n```\n\nIt's also possible to write a standalone Python script without needing to set up a whole project like so:\n\n```python\n#!/usr/bin/env -S uv run --script\n# /// script\n# requires-python = \"\u003e=3.9\"\n# dependencies = [\n#     \"unstructured-client\",\n# ]\n# ///\n\nfrom unstructured_client import UnstructuredClient\n\nsdk = UnstructuredClient(\n  # SDK arguments\n)\n\n# Rest of script here...\n```\n\nOnce that is saved to a file, you can run it with `uv run script.py` where\n`script.py` can be replaced with the actual file name.\n\u003c!-- End SDK Installation [installation] --\u003e\n\n\n\u003c!-- Start Retries [retries] --\u003e\n## Retries\n\nSome of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.\n\nTo change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call:\n```python\nfrom unstructured_client import UnstructuredClient\nfrom unstructured_client.utils import BackoffStrategy, RetryConfig\n\n\nwith UnstructuredClient() as uc_client:\n\n    res = uc_client.destinations.create_connection_check_destinations(request={\n        \"destination_id\": \"d9795fb7-2135-4e48-a51d-009dd6ca38a1\",\n    },\n        RetryConfig(\"backoff\", BackoffStrategy(1, 50, 1.1, 100), False))\n\n    assert res.dag_node_connection_check is not None\n\n    # Handle response\n    print(res.dag_node_connection_check)\n\n```\n\nIf you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK:\n```python\nfrom unstructured_client import UnstructuredClient\nfrom unstructured_client.utils import BackoffStrategy, RetryConfig\n\n\nwith UnstructuredClient(\n    retry_config=RetryConfig(\"backoff\", BackoffStrategy(1, 50, 1.1, 100), False),\n) as uc_client:\n\n    res = uc_client.destinations.create_connection_check_destinations(request={\n        \"destination_id\": \"d9795fb7-2135-4e48-a51d-009dd6ca38a1\",\n    })\n\n    assert res.dag_node_connection_check is not None\n\n    # Handle response\n    print(res.dag_node_connection_check)\n\n```\n\u003c!-- End Retries [retries] --\u003e\n\n\n\u003c!-- Start Error Handling [errors] --\u003e\n## Error Handling\n\nHandling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.\n\nBy default, an API error will raise a errors.SDKError exception, which has the following properties:\n\n| Property        | Type             | Description           |\n|-----------------|------------------|-----------------------|\n| `.status_code`  | *int*            | The HTTP status code  |\n| `.message`      | *str*            | The error message     |\n| `.raw_response` | *httpx.Response* | The raw HTTP response |\n| `.body`         | *str*            | The response content  |\n\nWhen custom error responses are specified for an operation, the SDK may also raise their associated exceptions. You can refer to respective *Errors* tables in SDK docs for more details on possible exception types for each operation. For example, the `create_connection_check_destinations_async` method may raise the following exceptions:\n\n| Error Type                 | Status Code | Content Type     |\n| -------------------------- | ----------- | ---------------- |\n| errors.HTTPValidationError | 422         | application/json |\n| errors.SDKError            | 4XX, 5XX    | \\*/\\*            |\n\n### Example\n\n```python\nfrom unstructured_client import UnstructuredClient\nfrom unstructured_client.models import errors\n\n\nwith UnstructuredClient() as uc_client:\n    res = None\n    try:\n\n        res = uc_client.destinations.create_connection_check_destinations(request={\n            \"destination_id\": \"d9795fb7-2135-4e48-a51d-009dd6ca38a1\",\n        })\n\n        assert res.dag_node_connection_check is not None\n\n        # Handle response\n        print(res.dag_node_connection_check)\n\n    except errors.HTTPValidationError as e:\n        # handle e.data: errors.HTTPValidationErrorData\n        raise(e)\n    except errors.SDKError as e:\n        # handle exception\n        raise(e)\n```\n\u003c!-- End Error Handling [errors] --\u003e\n\n\u003c!-- Start Custom HTTP Client [http-client] --\u003e\n## Custom HTTP Client\n\nThe Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library.  In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance.\nDepending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls.\nThis allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly.\n\nFor example, you could specify a header for every request that this sdk makes as follows:\n```python\nfrom unstructured_client import UnstructuredClient\nimport httpx\n\nhttp_client = httpx.Client(headers={\"x-custom-header\": \"someValue\"})\ns = UnstructuredClient(client=http_client)\n```\n\nor you could wrap the client with your own custom logic:\n```python\nfrom unstructured_client import UnstructuredClient\nfrom unstructured_client.httpclient import AsyncHttpClient\nimport httpx\n\nclass CustomClient(AsyncHttpClient):\n    client: AsyncHttpClient\n\n    def __init__(self, client: AsyncHttpClient):\n        self.client = client\n\n    async def send(\n        self,\n        request: httpx.Request,\n        *,\n        stream: bool = False,\n        auth: Union[\n            httpx._types.AuthTypes, httpx._client.UseClientDefault, None\n        ] = httpx.USE_CLIENT_DEFAULT,\n        follow_redirects: Union[\n            bool, httpx._client.UseClientDefault\n        ] = httpx.USE_CLIENT_DEFAULT,\n    ) -\u003e httpx.Response:\n        request.headers[\"Client-Level-Header\"] = \"added by client\"\n\n        return await self.client.send(\n            request, stream=stream, auth=auth, follow_redirects=follow_redirects\n        )\n\n    def build_request(\n        self,\n        method: str,\n        url: httpx._types.URLTypes,\n        *,\n        content: Optional[httpx._types.RequestContent] = None,\n        data: Optional[httpx._types.RequestData] = None,\n        files: Optional[httpx._types.RequestFiles] = None,\n        json: Optional[Any] = None,\n        params: Optional[httpx._types.QueryParamTypes] = None,\n        headers: Optional[httpx._types.HeaderTypes] = None,\n        cookies: Optional[httpx._types.CookieTypes] = None,\n        timeout: Union[\n            httpx._types.TimeoutTypes, httpx._client.UseClientDefault\n        ] = httpx.USE_CLIENT_DEFAULT,\n        extensions: Optional[httpx._types.RequestExtensions] = None,\n    ) -\u003e httpx.Request:\n        return self.client.build_request(\n            method,\n            url,\n            content=content,\n            data=data,\n            files=files,\n            json=json,\n            params=params,\n            headers=headers,\n            cookies=cookies,\n            timeout=timeout,\n            extensions=extensions,\n        )\n\ns = UnstructuredClient(async_client=CustomClient(httpx.AsyncClient()))\n```\n\u003c!-- End Custom HTTP Client [http-client] --\u003e\n\n\u003c!-- Start IDE Support [idesupport] --\u003e\n## IDE Support\n\n### PyCharm\n\nGenerally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.\n\n- [PyCharm Pydantic Plugin](https://docs.pydantic.dev/latest/integrations/pycharm/)\n\u003c!-- End IDE Support [idesupport] --\u003e\n\n\n\u003c!-- Start SDK Example Usage [usage] --\u003e\n## SDK Example Usage\n\n### Example\n\n```python\n# Synchronous Example\nfrom unstructured_client import UnstructuredClient\n\n\nwith UnstructuredClient() as uc_client:\n\n    res = uc_client.destinations.create_connection_check_destinations(request={\n        \"destination_id\": \"d9795fb7-2135-4e48-a51d-009dd6ca38a1\",\n    })\n\n    assert res.dag_node_connection_check is not None\n\n    # Handle response\n    print(res.dag_node_connection_check)\n```\n\n\u003c/br\u003e\n\nThe same SDK client can also be used to make asychronous requests by importing asyncio.\n```python\n# Asynchronous Example\nimport asyncio\nfrom unstructured_client import UnstructuredClient\n\nasync def main():\n\n    async with UnstructuredClient() as uc_client:\n\n        res = await uc_client.destinations.create_connection_check_destinations_async(request={\n            \"destination_id\": \"d9795fb7-2135-4e48-a51d-009dd6ca38a1\",\n        })\n\n        assert res.dag_node_connection_check is not None\n\n        # Handle response\n        print(res.dag_node_connection_check)\n\nasyncio.run(main())\n```\n\u003c!-- End SDK Example Usage [usage] --\u003e\n\nRefer to the [API parameters page](https://docs.unstructured.io/api-reference/api-services/api-parameters) for all available parameters.\n\n\n## Configuration\n\n### Splitting PDF by pages\n\nSee [page splitting](https://docs.unstructured.io/api-reference/api-services/sdk#page-splitting) for more details.\n\nIn order to speed up processing of large PDF files, the client splits up PDFs into smaller files, sends these to the API concurrently, and recombines the results. `split_pdf_page` can be set to `False` to disable this.\n\nThe amount of workers utilized for splitting PDFs is dictated by the `split_pdf_concurrency_level` parameter, with a default of 5 and a maximum of 15 to keep resource usage and costs in check. The splitting process leverages `asyncio` to manage concurrency effectively.\nThe size of each batch of pages (ranging from 2 to 20) is internally determined based on the concurrency level and the total number of pages in the document. Because the splitting process uses `asyncio` the client can encouter event loop issues if it is nested in another async runner, like running in a `gevent` spawned task. Instead, this is safe to run in multiprocessing workers (e.g., using `multiprocessing.Pool` with `fork` context).\n\nExample:\n```python\nreq = operations.PartitionRequest(\n    partition_parameters=shared.PartitionParameters(\n        files=files,\n        strategy=\"fast\",\n        languages=[\"eng\"],\n        split_pdf_concurrency_level=8\n    )\n)\n```\n\n### Sending specific page ranges\n\nWhen `split_pdf_page=True` (the default), you can optionally specify a page range to send only a portion of your PDF to be extracted. The parameter takes a list of two integers to specify the range, inclusive. A ValueError is thrown if the page range is invalid.\n\nExample:\n```python\nreq = operations.PartitionRequest(\n    partition_parameters=shared.PartitionParameters(\n        files=files,\n        strategy=\"fast\",\n        languages=[\"eng\"],\n        split_pdf_page_range=[10,15],\n    )\n)\n```\n\n### Splitting PDF by pages - strict mode\n\nWhen `split_pdf_allow_failed=False` (the default), any errors encountered during sending parallel request will break the process and raise an exception. \nWhen `split_pdf_allow_failed=True`, the process will continue even if some requests fail, and the results will be combined at the end (the output from the errored pages will not be included).\n\nExample:\n```python\nreq = operations.PartitionRequest(\n    partition_parameters=shared.PartitionParameters(\n        files=files,\n        strategy=\"fast\",\n        languages=[\"eng\"],\n        split_pdf_allow_failed=True,\n    )\n)\n```\n\n\u003c!-- Start File uploads [file-upload] --\u003e\n## File uploads\n\nCertain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.\n\n\u003e [!TIP]\n\u003e\n\u003e For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.\n\u003e\n\n```python\nfrom unstructured_client import UnstructuredClient\nfrom unstructured_client.models import shared\n\n\nwith UnstructuredClient() as uc_client:\n\n    res = uc_client.general.partition(request={\n        \"partition_parameters\": {\n            \"files\": {\n                \"content\": open(\"example.file\", \"rb\"),\n                \"file_name\": \"example.file\",\n            },\n            \"split_pdf_page_range\": [\n                1,\n                10,\n            ],\n            \"vlm_model\": shared.VLMModel.GPT_4O,\n            \"vlm_model_provider\": shared.VLMModelProvider.OPENAI,\n        },\n    })\n\n    assert res.elements is not None\n\n    # Handle response\n    print(res.elements)\n\n```\n\u003c!-- End File uploads [file-upload] --\u003e\n\n\u003c!-- Start Resource Management [resource-management] --\u003e\n## Resource Management\n\nThe `UnstructuredClient` class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a [context manager][context-manager] and reuse it across the application.\n\n[context-manager]: https://docs.python.org/3/reference/datamodel.html#context-managers\n\n```python\nfrom unstructured_client import UnstructuredClient\ndef main():\n\n    with UnstructuredClient() as uc_client:\n        # Rest of application here...\n\n\n# Or when using async:\nasync def amain():\n\n    async with UnstructuredClient() as uc_client:\n        # Rest of application here...\n```\n\u003c!-- End Resource Management [resource-management] --\u003e\n\n\u003c!-- Start Debugging [debug] --\u003e\n## Debugging\n\nYou can setup your SDK to emit debug logs for SDK requests and responses.\n\nYou can pass your own logger class directly into your SDK.\n```python\nfrom unstructured_client import UnstructuredClient\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\ns = UnstructuredClient(debug_logger=logging.getLogger(\"unstructured_client\"))\n```\n\u003c!-- End Debugging [debug] --\u003e\n\n\u003c!-- No SDK Available Operations --\u003e\n\u003c!-- No Pagination --\u003e\n\u003c!-- No Server Selection --\u003e\n\u003c!-- No Authentication --\u003e\n\n\u003c!-- Placeholder for Future Speakeasy SDK Sections --\u003e\n\n### Maturity\n\nThis SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage\nto a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally\nlooking for the latest version.\n\n### Installation Instructions for Local Development\n\nThe following instructions are intended to help you get up and running with `unstructured-python-client` locally if you are planning to contribute to the project.\n\n* Using `pyenv` to manage virtualenv's is recommended but not necessary\n   * Mac install instructions. See [here](https://github.com/Unstructured-IO/community#mac--homebrew) for more detailed instructions.\n      * `brew install pyenv-virtualenv`\n      * `pyenv install 3.10`\n   * Linux instructions are available [here](https://github.com/Unstructured-IO/community#linux).\n\n* Create a virtualenv to work in and activate it, e.g. for one named `unstructured-python-client`:\n\n  `pyenv  virtualenv 3.10 unstructured-python-client`\n  `pyenv activate unstructured-python-client`\n\n* Run `make install` and `make test`\n\n### Contributions\n\nWhile we value open-source contributions to this SDK, this library is generated programmatically by Speakeasy. In order to start working with this repo, you need to:\n1. Install Speakeasy client locally https://github.com/speakeasy-api/speakeasy#installation\n2. Run `speakeasy auth login`\n3. Run `make client-generate`. This allows to iterate development with python client.\n\nThere are two important files used by `make client-generate`:\n1. `openapi.json` which is actually not stored here, [but fetched from unstructured-api](https://api.unstructured.io/general/openapi.json), represents the API that is supported on backend.\n2. `overlay_client.yaml` is a handcrafted diff that when applied over above, produces `openapi_client.json` which is used to generate SDK.\n\nOnce PR with changes is merged, Github CI will autogenerate the Speakeasy client in a new PR, using\nthe `openapi.json` and `overlay_client.yaml` You will have to manually bring back the human created lines in it.\n\nFeel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!\n\n### SDK Created by [Speakeasy](https://www.speakeasyapi.dev/docs/sdk-design/python/methodology-python)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Funstructured-io%2Funstructured-python-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Funstructured-io%2Funstructured-python-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Funstructured-io%2Funstructured-python-client/lists"}