Skip to content

Using dependencies

DeclarativeX allows you to use dependencies to inject values into your endpoints.

Supported dependencies

Currently, DeclarativeX supports the following dependencies:

Dependency Casted to Description
Path str to inject path parameters.
Query str to inject query parameters.
Header str to inject header values.
Cookie str to inject cookie values.
Json dict[str, Any] to inject the request json body.
JsonField Any to inject a field into the json body.
Form dict[str, Any] to inject the request form body.
FormField Any to inject a field into the form body.
Timeout float to inject a timeout. Overrides the default value of the httpx.Client.
FollowRedirects bool to inject follow redirects. Overrides the default value of the httpx.Client.

Declaring dependencies

Dependencies should be declared as Annotated types.

from declarativex import Path, Query, Header, Cookie, Json, JsonField, Form, FormField, Timeout, FollowRedirects


class MyConsumer(Consumer):

    @http.post("/users/{user_id}")
    async def some_endpoint(
        user_id: Annotated[str, Path()],
        csrf_token: Annotated[str, Query()],
        authorization: Annotated[str, Header()],
        ga_id: Annotated[str, Cookie()],
        json: Annotated[dict[str, Any], Json()],
        field_name: Annotated[str, JsonField("field_name")],
    ) -> httpx.Response:
        pass


consumer = MyConsumer.basic_sync(base_url="https://example.com")
consumer.some_endpoint(
    user_id="123456",
    csrf_token="123456",
    authorization="Bearer 123456",
    ga_id="123456",
    json={"some_data": "some_value"},
    field_name="field_value",
)

Providing your own type

You can provide your type as a first argument of Annotated, but note that it should be castable to the type of the dependency.

For example, you can use path_value: Annotated[int, Path()] to inject a path parameter as an int.

In this case, the type of the dependency will be int, but the value will be cast to str by the Path dependency.

This allows you to use Foo.bar(path_value=5) and have the path_value be injected as "5".

This example will produce an httpx.Request object that looks like this:

POST https://example.com/users/123456?csrf_token=123456 HTTP/1.1
Content-Type: application/json
Authorization: Bearer 123456
Cookie: ga_id=123456

{
    "some_data": "some_value",
    "field_name": "field_value"
}