Skip to main content

ascender-httpclient

This project has been archived.

The maintainers of this project have marked this project as archived. No new releases are expected.

Project description

Ascender HTTP Client (aschttp)

ascender-httpclient (aschttp) is a powerful and extendable HTTP client for the Ascender Framework. It supports synchronous, asynchronous, and streaming HTTP requests with clean dependency injection, interceptors, and multi-instance configurations.

Features

  • Dependency Injection: Easily inject HTTPClient into any service.
  • Interceptor Support: Create and manage interceptors to customize request handling.
  • Multiple HTTPClient Instances: Use custom HTTP client classes alongside the default singleton.
  • Async and Streaming Requests: Built-in support for asynchronous and streaming HTTP requests.
  • Command Line Integration: Generate interceptors with a simple CLI command.

Installation

To install the package, in your project type:

poetry add ascender-httpclient

Ensure that the Ascender Framework is installed and properly configured.


Initialization

To initialize aschttp, configure ProvideHTTPClient() in your bootstrap.py:

...
from aschttp import ProvideHTTPClient

appBootstrap: IBootstrap = {
    "providers": [
        DatabaseProvider(ORMEnum.SQLALCHEMY, DATABASE_CONNECTION),
        ProvideControllers([
            ControllersModule
        ]),
        ProvideHTTPClient()
    ]
}

Usage

Injecting HTTPClient

To inject the HTTP client into any service:

from ascender.common import Injectable
from ascender.contrib.services import Service
from aschttp import HTTPClient

@Injectable()
class MainService(Service):
    def __init__(self, http: HTTPClient):
        self.http = http

Making Requests

GET Request

from controllers.dtos.test_dto import TestDTO

@Injectable()
class MainService(Service):
    def __init__(self, http: HTTPClient):
        self.http = http
    
    async def make_get_request(self):
        response = await self.http.get(TestDTO, url="http://api.example.com/get")
        assert isinstance(response, TestDTO)
        return response

POST Request

from controllers.dtos.test_dto import TestDTO

@Injectable()
class MainService(Service):
    def __init__(self, http: HTTPClient):
        self.http = http
    
    async def make_post_request(self, dto: TestDTO):
        response = await self.http.post(str, url="http://api.example.com/post", content=dto)
        assert isinstance(response, str)
        return response

Streaming Request

@Injectable()
class MainService(Service):
    def __init__(self, http: HTTPClient):
        self.http = http
    
    def make_streaming_request(self):
        self.http.stream(str, method="GET", url="http://api.example.com/stream").subscribe(
            on_next=lambda r: print(r),
            on_error=lambda err: print(err)
        )

Custom HTTP Clients

To use multiple HTTP client instances:

  1. Define a custom HTTP client class:
from aschttp import HTTPClient

class MyHTTP(HTTPClient):
    pass
  1. Register the custom HTTP client in bootstrap.py:
from myclient import MyHTTP

appBootstrap: IBootstrap = {
    "providers": [
        ProvideHTTPClient(),
        ProvideHTTPClient(client_instance=MyHTTP)
    ]
}

Interceptors

Interceptors allow you to modify HTTP requests before they are sent.

Generate an Interceptor

Use the Ascender CLI to generate an interceptor:

ascender run aschttp:generate interceptor interceptors/custom

Output:

$ CREATE interceptors/custom_interceptor.py (164 bytes)

Implementing an Interceptor

Example custom interceptor:

from httpx import Request
from aschttp.types.interceptors import Interceptor

class CustomInterceptor(Interceptor):
    def __init__(self) -> None:  # for dependency injection, REQUIRED
        pass

    async def handle_request(self, request: Request) -> Request:
        # Modify the request here...
        print("custom interceptor works!")
        return request

Registering an Interceptor

Register the interceptor in bootstrap.py:

from processes.custom_interceptor import MyInterceptor

appBootstrap: IBootstrap = {
    "providers": [
        ProvideHTTPClient(interceptors=[
            MyInterceptor
        ])
    ]
}

Key Concepts

Singleton HTTPClient

The HTTPClient is a singleton by default, ensuring a single instance throughout the framework. However, you can register multiple clients using the ProvideHTTPClient factory, all you need is to change it's client_instance parameter into your custom, example provided in Custom HTTP Clients section.

Interceptors

Interceptors allow request modification before sending. Use them for:

  • Adding headers
  • Logging requests
  • Transforming request payloads

Streaming

The stream() method uses an observable pattern to handle streaming responses efficiently utilizing RxPY.


Command Reference

Generate Interceptor

ascender run aschttp:generate interceptor <path/to/interceptor>

Examples Repository

Find more examples and best practices in the official Ascender Framework examples repository.


Contribution

Contributions are welcome! Submit issues, feature requests, or pull requests via GitHub.


License

The ascender-httpclient package is licensed under the MIT License.

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

ascender_httpclient-0.1.0.tar.gz (5.9 kB view details)

Uploaded Source

Built Distribution

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

ascender_httpclient-0.1.0-py3-none-any.whl (7.9 kB view details)

Uploaded Python 3

File details

Details for the file ascender_httpclient-0.1.0.tar.gz.

File metadata

  • Download URL: ascender_httpclient-0.1.0.tar.gz
  • Upload date:
  • Size: 5.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.3 CPython/3.11.10 Darwin/23.6.0

File hashes

Hashes for ascender_httpclient-0.1.0.tar.gz
Algorithm Hash digest
SHA256 dc017ce8da3fbec39c7bd0d7dc46885a5ccd46fd634746c376984ccde734ef51
MD5 96cdae925e0e2804eae5c9ee7760e7be
BLAKE2b-256 631f6ff266f6bd0cce68a5333934bd63c44c6d54110518c06d97c96b4cff8729

See more details on using hashes here.

File details

Details for the file ascender_httpclient-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for ascender_httpclient-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5029c6aee97935d89c1b542f30f01204fbc4702b977d2c2c7ab97fb8c30f9ad1
MD5 c9c4927a6ccd57941bad0f60cf8f0b54
BLAKE2b-256 dab0249bec5fd23633252f31eaddbb374d43f636cbea746ab74d7cb345180788

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