clientfactory


Nameclientfactory JSON
Version 0.6.3 PyPI version JSON
download
home_pageNone
SummaryA framework for building API clients with minimal boilerplate
upload_time2024-12-18 00:05:21
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT
keywords api client rest http
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ClientFactory

A Python framework for building API clients with minimal boilerplate while maintaining full configurability and extensibility.

## Features

- **Declarative API Definition**: Define your API structure using Python classes and decorators
- **Multiple Authentication Methods**: Built-in support for:
  - API Key authentication (header or query parameter)
  - OAuth 2.0 (client credentials, authorization code)
  - Session-based authentication with browser automation
  - Basic HTTP authentication
  - Token-based authentication
  - Custom authentication handlers
- **Resource Management**:
  - Organize endpoints into logical resource groups
  - Support for nested resources
  - Automatic URL construction
  - Path parameter handling
- **Request Processing**:
  - Pre-processing hooks for request modification
  - Post-processing hooks for response transformation
  - Automatic retries with configurable backoff
  - File upload support with progress tracking
- **Session Management**:
  - Persistent sessions with encryption
  - Cookie handling
  - Proxy support
  - Custom header management
- **Type Safety**: Full type hinting support for better IDE integration
- **Extensibility**: Every component is designed to be extended and customized

## Installation

```bash
pip install clientfactory
```

## Quick Start

### Basic Usage

```python
from clientfactory import Client, resource, get, post, ApiKeyAuth

class GitHub(Client):
    baseurl = "https://api.github.com"
    auth = ApiKeyAuth.header("your-token", "Authorization", prefix="Bearer")

    @resource
    class Repos:
        @get("user/repos")
        def list_repos(self): pass

        @post("user/repos")
        def create_repo(self, name: str, private: bool = False):
            return {"name": name, "private": private}

# Use the client
github = GitHub()
repos = github.repos.list_repos()
```

### Request Processing

```python
from clientfactory import Client, resource, get, preprocess, postprocess
from clientfactory.utils import Request, Response

class DataAPI(Client):
    baseurl = "https://api.example.com"

    @resource
    class Data:
        @preprocess
        def add_timestamp(self, request: Request) -> Request:
            """Add timestamp to all requests"""
            return request.WITH(
                headers={"X-Timestamp": str(time.time())}
            )

        @postprocess
        def extract_data(self, response: Response) -> dict:
            """Extract data field from response"""
            return response.json()["data"]

        @get("data/{id}")
        def get_data(self, id: str): pass
```

### File Uploads

```python
from clientfactory import Client, resource, post, UploadConfig
from clientfactory.utils import FileUpload

class Storage(Client):
    baseurl = "https://storage.example.com"

    @resource
    class Files:
        def progress(self, current: int, total: int):
            print(f"Uploaded {current}/{total} bytes")

        @post("upload")
        def upload(self, file: str):
            uploader = FileUpload(
                config=UploadConfig(
                    progresscallback=self.progress
                )
            )
            return uploader.multipart(
                url=self.url + "/upload",
                files={"file": file}
            )
```

### OAuth Authentication

```python
from clientfactory import Client, OAuth2Auth, resource, get

class ServiceAPI(Client):
    baseurl = "https://api.service.com"
    auth = OAuth2Auth.clientcredentials(
        clientid="your-client-id",
        clientsecret="your-client-secret",
        tokenurl="https://auth.service.com/token"
    )

    @resource
    class Users:
        @get("users/me")
        def me(self): pass
```

### Builder Pattern

```python
from clientfactory import ClientBuilder, ApiKeyAuth

# Create client programmatically
client = (ClientBuilder()
    .baseurl("https://api.example.com")
    .auth(ApiKeyAuth.header("your-key"))
    .sessioncfg(verify=False)  # Disable SSL verification
    .requestconfig(timeout=30.0)
    .headers({
        "User-Agent": "MyApp/1.0",
        "Accept": "application/json"
    })
    .build())
```

### Session Persistence

```python
from clientfactory import Client, DiskPersist, PersistConfig

class WebApp(Client):
    baseurl = "https://webapp.example.com"

    def __init__(self):
        # Setup encrypted session persistence
        self.persist = DiskPersist(
            config=PersistConfig(
                path="~/.myapp/session",
                encrypt=True
            )
        )
        super().__init__()
```

## Advanced Usage

For more advanced usage examples, including:
- Custom authentication handlers
- Complex request/response processing
- Browser automation for web apps
- Request retries and backoff strategies
- Resource hierarchies
- Error handling

Visit our [Advanced Usage Guide](https://clientfactory.readthedocs.io/advanced/).

## Development

```bash
# Clone the repository
git clone https://github.com/schizoprada/clientfactory.git
cd clientfactory

# Create a virtual environment
python -m venv venv
source venv/bin/activate  # or `venv\Scripts\activate` on Windows

# Install development dependencies
pip install -e ".[test,docs]"

# Run tests
pytest

# Build documentation
cd docs
make html
```

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.


## Support

- Documentation: [ReadTheDocs](https://clientfactory.readthedocs.io/)
- Issues: [GitHub Issues](https://github.com/schizoprada/clientfactory/issues)
- Discussions: [GitHub Discussions](https://github.com/schizoprada/clientfactory/discussions)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "clientfactory",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "api, client, rest, http",
    "author": null,
    "author_email": "Joel Yisrael <joel@highlyawear.com>",
    "download_url": "https://files.pythonhosted.org/packages/2c/77/1e6811d0d93a968046562572ea681e04ed2eb3a400397dd24000c4fefae8/clientfactory-0.6.3.tar.gz",
    "platform": null,
    "description": "# ClientFactory\n\nA Python framework for building API clients with minimal boilerplate while maintaining full configurability and extensibility.\n\n## Features\n\n- **Declarative API Definition**: Define your API structure using Python classes and decorators\n- **Multiple Authentication Methods**: Built-in support for:\n  - API Key authentication (header or query parameter)\n  - OAuth 2.0 (client credentials, authorization code)\n  - Session-based authentication with browser automation\n  - Basic HTTP authentication\n  - Token-based authentication\n  - Custom authentication handlers\n- **Resource Management**:\n  - Organize endpoints into logical resource groups\n  - Support for nested resources\n  - Automatic URL construction\n  - Path parameter handling\n- **Request Processing**:\n  - Pre-processing hooks for request modification\n  - Post-processing hooks for response transformation\n  - Automatic retries with configurable backoff\n  - File upload support with progress tracking\n- **Session Management**:\n  - Persistent sessions with encryption\n  - Cookie handling\n  - Proxy support\n  - Custom header management\n- **Type Safety**: Full type hinting support for better IDE integration\n- **Extensibility**: Every component is designed to be extended and customized\n\n## Installation\n\n```bash\npip install clientfactory\n```\n\n## Quick Start\n\n### Basic Usage\n\n```python\nfrom clientfactory import Client, resource, get, post, ApiKeyAuth\n\nclass GitHub(Client):\n    baseurl = \"https://api.github.com\"\n    auth = ApiKeyAuth.header(\"your-token\", \"Authorization\", prefix=\"Bearer\")\n\n    @resource\n    class Repos:\n        @get(\"user/repos\")\n        def list_repos(self): pass\n\n        @post(\"user/repos\")\n        def create_repo(self, name: str, private: bool = False):\n            return {\"name\": name, \"private\": private}\n\n# Use the client\ngithub = GitHub()\nrepos = github.repos.list_repos()\n```\n\n### Request Processing\n\n```python\nfrom clientfactory import Client, resource, get, preprocess, postprocess\nfrom clientfactory.utils import Request, Response\n\nclass DataAPI(Client):\n    baseurl = \"https://api.example.com\"\n\n    @resource\n    class Data:\n        @preprocess\n        def add_timestamp(self, request: Request) -> Request:\n            \"\"\"Add timestamp to all requests\"\"\"\n            return request.WITH(\n                headers={\"X-Timestamp\": str(time.time())}\n            )\n\n        @postprocess\n        def extract_data(self, response: Response) -> dict:\n            \"\"\"Extract data field from response\"\"\"\n            return response.json()[\"data\"]\n\n        @get(\"data/{id}\")\n        def get_data(self, id: str): pass\n```\n\n### File Uploads\n\n```python\nfrom clientfactory import Client, resource, post, UploadConfig\nfrom clientfactory.utils import FileUpload\n\nclass Storage(Client):\n    baseurl = \"https://storage.example.com\"\n\n    @resource\n    class Files:\n        def progress(self, current: int, total: int):\n            print(f\"Uploaded {current}/{total} bytes\")\n\n        @post(\"upload\")\n        def upload(self, file: str):\n            uploader = FileUpload(\n                config=UploadConfig(\n                    progresscallback=self.progress\n                )\n            )\n            return uploader.multipart(\n                url=self.url + \"/upload\",\n                files={\"file\": file}\n            )\n```\n\n### OAuth Authentication\n\n```python\nfrom clientfactory import Client, OAuth2Auth, resource, get\n\nclass ServiceAPI(Client):\n    baseurl = \"https://api.service.com\"\n    auth = OAuth2Auth.clientcredentials(\n        clientid=\"your-client-id\",\n        clientsecret=\"your-client-secret\",\n        tokenurl=\"https://auth.service.com/token\"\n    )\n\n    @resource\n    class Users:\n        @get(\"users/me\")\n        def me(self): pass\n```\n\n### Builder Pattern\n\n```python\nfrom clientfactory import ClientBuilder, ApiKeyAuth\n\n# Create client programmatically\nclient = (ClientBuilder()\n    .baseurl(\"https://api.example.com\")\n    .auth(ApiKeyAuth.header(\"your-key\"))\n    .sessioncfg(verify=False)  # Disable SSL verification\n    .requestconfig(timeout=30.0)\n    .headers({\n        \"User-Agent\": \"MyApp/1.0\",\n        \"Accept\": \"application/json\"\n    })\n    .build())\n```\n\n### Session Persistence\n\n```python\nfrom clientfactory import Client, DiskPersist, PersistConfig\n\nclass WebApp(Client):\n    baseurl = \"https://webapp.example.com\"\n\n    def __init__(self):\n        # Setup encrypted session persistence\n        self.persist = DiskPersist(\n            config=PersistConfig(\n                path=\"~/.myapp/session\",\n                encrypt=True\n            )\n        )\n        super().__init__()\n```\n\n## Advanced Usage\n\nFor more advanced usage examples, including:\n- Custom authentication handlers\n- Complex request/response processing\n- Browser automation for web apps\n- Request retries and backoff strategies\n- Resource hierarchies\n- Error handling\n\nVisit our [Advanced Usage Guide](https://clientfactory.readthedocs.io/advanced/).\n\n## Development\n\n```bash\n# Clone the repository\ngit clone https://github.com/schizoprada/clientfactory.git\ncd clientfactory\n\n# Create a virtual environment\npython -m venv venv\nsource venv/bin/activate  # or `venv\\Scripts\\activate` on Windows\n\n# Install development dependencies\npip install -e \".[test,docs]\"\n\n# Run tests\npytest\n\n# Build documentation\ncd docs\nmake html\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n\n## Support\n\n- Documentation: [ReadTheDocs](https://clientfactory.readthedocs.io/)\n- Issues: [GitHub Issues](https://github.com/schizoprada/clientfactory/issues)\n- Discussions: [GitHub Discussions](https://github.com/schizoprada/clientfactory/discussions)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A framework for building API clients with minimal boilerplate",
    "version": "0.6.3",
    "project_urls": {
        "Documentation": "https://clientfactory.readthedocs.io/",
        "Homepage": "https://github.com/schizoprada/clientfactory",
        "Repository": "https://github.com/schizoprada/clientfactory.git"
    },
    "split_keywords": [
        "api",
        " client",
        " rest",
        " http"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f3f3c390439ec1ed3cf27fea2e4ed45caddd8355b19b17ff2f13636a724ebbe2",
                "md5": "993daf442b9d8f46fe7fafb68f5163cb",
                "sha256": "b4b833fdaf9e558a8b4061773714a7a25d0c6be5c833bf907bb6e36d7d5ab388"
            },
            "downloads": -1,
            "filename": "clientfactory-0.6.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "993daf442b9d8f46fe7fafb68f5163cb",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 55704,
            "upload_time": "2024-12-18T00:05:18",
            "upload_time_iso_8601": "2024-12-18T00:05:18.786319Z",
            "url": "https://files.pythonhosted.org/packages/f3/f3/c390439ec1ed3cf27fea2e4ed45caddd8355b19b17ff2f13636a724ebbe2/clientfactory-0.6.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2c771e6811d0d93a968046562572ea681e04ed2eb3a400397dd24000c4fefae8",
                "md5": "1ba9a4c3b924755bd0d7c3629b0158f0",
                "sha256": "c3813a9dc4ec031dee27037e74ca39f36425b0d643896a73b2cf1900e4d27c10"
            },
            "downloads": -1,
            "filename": "clientfactory-0.6.3.tar.gz",
            "has_sig": false,
            "md5_digest": "1ba9a4c3b924755bd0d7c3629b0158f0",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 66185,
            "upload_time": "2024-12-18T00:05:21",
            "upload_time_iso_8601": "2024-12-18T00:05:21.490953Z",
            "url": "https://files.pythonhosted.org/packages/2c/77/1e6811d0d93a968046562572ea681e04ed2eb3a400397dd24000c4fefae8/clientfactory-0.6.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-18 00:05:21",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "schizoprada",
    "github_project": "clientfactory",
    "github_not_found": true,
    "lcname": "clientfactory"
}
        
Elapsed time: 0.49208s