GithubHelp home page GithubHelp logo

floydya / declarativex Goto Github PK

View Code? Open in Web Editor NEW
20.0 2.0 2.0 1.02 MB

Your Declarative HTTP client library on Python

Home Page: https://declarativex.dev/

License: MIT License

Python 99.79% Makefile 0.21%
fastapi httpx pydantic async declarative sync api json python python-types

declarativex's Introduction

PyPI - Python Version PyPI - Downloads Coverage

DeclarativeX: Your Declarative HTTP Client ๐Ÿš€

Why Choose DeclarativeX? ๐Ÿคทโ€โ™‚๏ธ

Sick of writing boilerplate for every HTTP request? Headers, JSON parsing, and all that jazz?

Say hello to DeclarativeX!

We handle the nitty-gritty so you can focus on what really countsโ€”your core logic.

๐ŸŒŸ Key Features

  • Declarative Goodness: Decorators make your life easy. Just add and go!
  • Function Over Form: No need for classes. Check the docs for function-based setups.
  • Data Validation: Using Pydantic? We've got your robust validation needs covered.
  • Async Ready: Need it fast? We're async-compatible.
  • Rate Limiting: Stay on the good side of APIs with built-in rate limiting.
  • Authentication: Add authentication with a single line of code.
  • Automatic Retries: We retry failed requests automatically(or reject, if you prefer).
  • Middleware Support: Add your custom logic with ease.
  • Auto Body Parsing: Skip manual parsing. Use a dataclass or Pydantic model for auto-magic.
  • GraphQL: We support GraphQL queries and mutations out of the box.

Installation ๐Ÿ› ๏ธ

pip install declarativex

Available extras ๐ŸŽ

DeclarativeX comes with a few extras that you can install separately. Here's a list of available extras:

  • http2 - HTTP/2 support
  • graphql - GraphQL support
  • brotli - Brotli compression support

To install an extra, just add it to the end of the command:

pip install declarativex[http2,graphql,brotli]

Docs ๐Ÿ“–

Find all the details at https://declarativex.dev.

Show Some Love โค๏ธ

Every contribution counts and is super appreciated! ๐Ÿ™

Liking what you see? Support the creator to keep this project thriving.

ko-fi

declarativex's People

Contributors

apxdono avatar dependabot[bot] avatar floydya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

declarativex's Issues

Explicit type-hinting httpx.Response should yield response object

Description

TL;DR This is a really good thing to have, as type-hinting is preserved.

While not specified in the documentation it's technically possible to explicitly type-hint client methods with httpx.Request.
When method is type-hinted with httpx.Request, Pydantic will raise pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'httpx.Response'>.

Steps to Reproduce

import httpx
from declarativex import BaseClient, http


class DummyUsersClient(BaseClient):
    # pylint: disable=unused-argument
    base_url = "https://dummyjson.com"

    @http("GET", "/users/{user_id}")
    def get_user(self, user_id: int, ) -> httpx.Response:
        ...


if __name__ == "__main__":
    response = DummyUsersClient().get_user(1)
    print(response)

Expected Behavior

Behavior should be the same as if you omit type-hinting. This should be a trivial thing to add, as absence of type-hint is already checked here.

Actual Behavior

(omitted)
.../site-packages/pydantic/_internal/_generate_schema.py", line 397, in _unknown_type_schema
    raise PydanticSchemaGenerationError(
pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'httpx.Response'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.

If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.

For further information visit https://errors.pydantic.dev/2.6/u/schema-for-unknown-type

Environment

  • Python version: 3.11.7
  • DeclarativeX version: 1.6.5

Allow consumption of preconfigured httpx client

Description

Today's approach for declarativex executors (both sync and async) creates new clients under the hood. This works fine as long as you are fine with basic httpx settings. Use Case section lists a number of additional features that can be unlocked if declarativex API can consume pre-configured httpx (and other) clients.

Use Case

  • Support for cookie retention between API calls
  • Support for self-signed certificates added at runtime (not via OS certificate chains)
  • Support for httpx event hooks. This is a big one since declarativex Middleware consumes transformed responses, while httpx event hook can access raw request.
  • Advanced transport usage
  • Other httpx benefits
  • Async settings

Proposed Solution

Introduce new base_client (or client) BaseClient property (similar to base_url, timeout and others) / @http argument. When supplied respective Executor uses supplied client inside _execute method instead of creating new one during each _execute call.

The drawback is that follow_redirects, http2 and proxies settings will be ignored. Users must set those inside the client, but if they opt for custom client, they kinda know what they're doing.

Alternatives

Custom executor can be used instead, but this implies creation of custom @http annotation, which is kinda ugly.

Will try to file a PR once I get spare time to work on this.

Sync and async clients

When exposing a client to third parties, it would be nice to allow them to choose between a sync and an async one. But it is impossible to do it without having to write the client twice (I will love to be corrected if I'm wrong). Is it possible to have an API so we can get the async version from the sync one?

Preserving type-hints of decorated functions

Description

Today if you annotate a function or class method with @http decorator you're effectively erasing any type information of this function. Most likely this is a side effect of existing typing information of utils.py Decorator class:

    def __call__(
        self, func: Callable[..., ReturnType]
    ) -> Callable[..., ReturnType]:

At least this is the case with current Linux version of VSCode

Version: 1.86.0
Commit: 05047486b6df5eb8d44b2ecd70ea3bdf775fd937
Date: 2024-01-31T10:27:46.147Z
Electron: 27.2.3
ElectronBuildId: 26495564
Chromium: 118.0.5993.159
Node.js: 18.17.1
V8: 11.8.172.18-electron.0
OS: Linux x64 6.7.3-zen1-2-zen

image

At the same time the issue is not present in PyCharm, most likely because PyCharm relies on own implementation of syntax parser.

Use Case

Proper type hinting is important for many developers and it would be nice to preserve it using "pythonic means" across various IDEs.

Proposed Solution

Starting from Python 3.10 it's possible to correctly type hint decorators in order to preserve parameter information. More info about ParamSpec can be found in PEP-612 or in Python's Typing docs.

Versions prior to 3.10 will have to suffer a "no type hints" VSCode experience (unless VSCode fixes it somehow via plugin, which is doubtful).

The fix itself is pretty straightforward: properly typing Decorator#call is enough to fix VSCode type resolution:

from typing import ParamSpec

OriginalParams = ParamSpec("OriginalParams")
...
class Decorator:
    ...
    def __call__(
        self, func: Callable[OriginalParams, ReturnType]
    ) -> Callable[OriginalParams, ReturnType]:

image

Proposed PR with fix: #39

Alternatives

None as of now

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.