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.

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.1.tar.gz (61.5 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.1-py3-none-any.whl (80.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: clientfactory-0.7.1.tar.gz
  • Upload date:
  • Size: 61.5 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.1.tar.gz
Algorithm Hash digest
SHA256 43b78704719a8764e9f986d235dc17781053cd7839a1bc72cdc448335226927e
MD5 88aa6e48179afa8a89f312644f881516
BLAKE2b-256 c8ff34af15d91aa8be14732834928eadeed9a1620a645bc78f79fb763863d08b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: clientfactory-0.7.1-py3-none-any.whl
  • Upload date:
  • Size: 80.8 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 fbd0457c952b662d010625ca9008579c9e7fd7bc6757f8198f2d024ec9d040be
MD5 1b69a5d3fee7cddd33344a553ebb9e2f
BLAKE2b-256 9e545c8e15ce64ad566d38408d52cb2c10c1f2c80c93695234685480b2638d0a

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