Skip to main content

A framework for building API clients with minimal boilerplate

Project description

ClientFactory

A declarative framework for building API clients with minimal boilerplate that supports multiple protocols and authentication methods.

Table of Contents

  1. Overview
  2. Architecture
  3. Features
  4. Installation
  5. Usage Example
  6. Core Concepts
  7. Contributing
  8. License

Overview

ClientFactory is a Python library designed to streamline the creation and management of API clients by using a declarative syntax. It reduces boilerplate code and provides a structured approach to handle various API protocols, authentication schemes, and session management.

Architecture

Client and Resources

In ClientFactory, the Client class is central, serving as a container for resources, authentication, and session management. Resources are nested classes within a Client class, representing different logical groupings of API endpoints.

  • Automatic Resource Path: If no path is specified for a resource, it defaults to using the resource's class name in lowercase as the path.

  • Resource Instantiation: Upon client instantiation, resource instances are accessible as lowercase attributes of the client object. For example:

    class ExampleClient(Client):
        class SomeResource(Resource):
            pass
    
    client = ExampleClient()
    # Access resource by its lowercase name
    client.someresource
    

URL Construction

ClientFactory automates the construction of API request URLs:

  • Base URL: Defined at the Client level.
  • Resource Path: Each resource class appends its path to the base URL.
  • Method Path and Parameters: Methods can specify additional paths and parameters, replacing placeholders with method arguments.

Order of Operations in Method Execution

The sequence of operations for method execution includes:

  1. Path Construction: Combining base URL, resource, and method paths. Placeholders in the path are replaced by actual method arguments.
  2. Payload Preparation: Validating and transforming the method's payload.
  3. Request Processing: Applying preprocessors and configuring request headers and parameters.
  4. Authentication Enforcement: Appending authentication details to the request if required.
  5. Request Execution: Sending the HTTP request.
  6. Response Handling: Applying postprocessors and returning the response.

Below is a visual representation of these operations:

+------------------+
|      Client      |
| (baseurl: ...)   |
+------------------+
          |
          v
+------------------+     +--------------------------+
|     Resource     |     |         Session          |
| (path: /api)     |<--> | (auth, headers, cookies) |
+------------------+     +--------------------------+
        |
        v
+-------------------+    +----------------------+
|   ResourceMethod  |--> | URL Construction     |
| (e.g., get_user)  |    +----------------------+
| @get("{id}")      |    +----------------------+
+-------------------+--> | Payload Validation   |
                         +----------------------+
...                    -->| Preprocessing       |
                         +----------------------+
                         | Authentication       |
                         +----------------------+
                         | Request Execution    | --> {API Request}
                         +----------------------+
                         | Postprocessing       |
                         +----------------------+
                         | Response Handling    | <-- {API Response}
                         +----------------------+
                         | Return to Method     |
                         +----------------------+

Features

Declarative API Definition

Easily define API clients using classes and decorators:

from clientfactory import Client, resource, get, post

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

    @resource
    class Users:
        @get("{id}")
        def get_user(self, id): pass

        @post
        def create_user(self, **data): pass

Authentication Support

ClientFactory supports various authentication strategies including:

  • Bearer Token
  • Basic Auth
  • API Key (can be sent in the header or as a query string)
  • OAuth 2.0 (supports multiple OAuth flows)
  • DPoP (Demonstration of Proof-of-Possession)

Multi-Protocol Support

Leverage different protocol backends:

  • REST: Basic HTTP protocols with method decorators.
  • GraphQL: Easily define GraphQL queries and operations.
  • Algolia: Optimized search request handling.

Session Management

  • Enhanced Sessions: Allows for state management, persistent cookie storage, and dynamic header settings.

State Persistence

Maintain and persist session state across requests using JSON or Pickle files:

from clientfactory.session.state import JSONStateStore
from clientfactory.decorators import jsonstore

@jsonstore
class StateManager:
    path = "session_state.json"

Parameter Handling

Schemas define validation and transformation rules for request data, ensuring consistency and reducing potential errors. Automatic docstring construction is provided for payloads, offering clear guidance on required and optional parameters.

Specialized Resources

Search Resources

Use searchresource to create search functionality. The search method is dynamically generated unless specified with oncall to make the resource a callable object.

class SearchClient(Client):
    @searchresource
    class AdvancedSearch:
        oncall = True

Call via client.advancedsearch() if oncall is True, otherwise use client.advancedsearch.search().

Managed Resources (CRUD)

Predefined CRUD operations using a structured interface:

from clientfactory import Client, managedresource

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

    @managedresource
    class Users:
        operations = {
            "create": createop(payload=user_payload),
            "get": readop("{id}"),
            "update": updateop("{id}", payload=user_payload),
            "delete": deleteop("{id}"),
            "list": listop()
        }

Installation

Install ClientFactory using pip:

pip install clientfactory

Usage Example

Here’s a complete example defining and using a client with authentication and resource methods:

from clientfactory import Client, resource, get, post
from clientfactory.auth import TokenAuth

class ExampleClient(Client):
    baseurl = "https://api.example.com"
    auth = TokenAuth.Bearer("access-token")

    @resource
    class Users:
        @get("{id}")
        def get_user(self, id):
            """Retrieve a user by ID"""
            pass

        @post
        def create_user(self, **data):
            """Create a new user"""
            pass

client = ExampleClient()

# Retrieve a user by ID
user_response = client.users.get_user(id=1)

# Create a new user
create_response = client.users.create_user(name="John Doe", email="john@example.com")

Core Concepts

  • Client: The container managing resources, authentication, and session settings.
  • Resource: Encapsulates related API endpoints as methods, with automatic URL construction and Payload handling.
  • Payload: Manages the schema for request parameters, enforcing validation and transformation rules.
  • Auth: Configures various authentication schemes to ensure secure API communication.
  • Session: Manages state and communication context between requests.
  • Backend: Handles different protocols, allowing for flexibility and custom integrations (e.g., REST, GraphQL).

Contributing

Contributions are welcome! Feel free to submit a Pull Request with enhancements, features, or bug fixes.

License

This project is licensed under the MIT License. See the LICENSE file for details.


This expanded readme now includes detailed guidance on architecture, url construction, method execution sequence, and specifics about resource management, providing deeper insights for developers using ClientFactory.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

clientfactory-0.7.0.tar.gz (61.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

clientfactory-0.7.0-py3-none-any.whl (80.9 kB view details)

Uploaded Python 3

File details

Details for the file clientfactory-0.7.0.tar.gz.

File metadata

  • Download URL: clientfactory-0.7.0.tar.gz
  • Upload date:
  • Size: 61.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for clientfactory-0.7.0.tar.gz
Algorithm Hash digest
SHA256 6405dbacbbd6d1596b352e39d6ded3643036119cc2e08bc3d123b4502dcb0cf3
MD5 48ed05f0af6a5235fd42240f184a03f0
BLAKE2b-256 829324a7a4c2b2d9c486bebed088b47f8a37f8d454778d9d139e8933e8f7a649

See more details on using hashes here.

File details

Details for the file clientfactory-0.7.0-py3-none-any.whl.

File metadata

  • Download URL: clientfactory-0.7.0-py3-none-any.whl
  • Upload date:
  • Size: 80.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for clientfactory-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b2414c1ed3955a1fa2f38f813f8c2a640dca20c4504762e88a0f923e1b1a05e6
MD5 92403bead9db59dcb27692efda337bf8
BLAKE2b-256 14dd77e23a7890b303d5f138b16286805cc32553461c526bdffcf05f3f1e8389

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page