API Reference

Component

A component for HTTP sending. (Header, Query, Path, Body)

class Component

Base class for request-parameter components.

Components can be used in annotations to map a function parameter to a header, query string, path placeholder, or request body.

component_name

Optional transformation used for the component key sent on the wire.

Type:

Callable[[str], str]

classmethod custom_name(name: str) → Self

Return a component instance with a fixed transmitted name.

Parameters:

name (str) – Name used in the request instead of the Python parameter name.

Raises:

NotImplementedError – If the component does not support renamed fields, such as Path or Body.

classmethod to_camel() → Self

Return a component instance that converts its key to camel case.

Raises:

NotImplementedError – If the component does not support renamed fields.

classmethod to_pascal() → Self

Return a component instance that converts its key to Pascal case.

Raises:

NotImplementedError – If the component does not support renamed fields.

class Body

Bases: _BodyFileComponent, _UnsupportedCustomNameComponent

Mark a parameter as the complete request body.

dict, list, and tuple values are encoded as JSON; other values (including file-like values) are sent as raw body data. A Body parameter cannot be combined with BodyJson or BodyForm parameters. metadata() adds filename and content-type metadata without changing the raw-body encoding.

class BodyJson

Bases: Component

Mark a parameter as a field in a JSON request body.

Use custom_key() to place the value under a different or nested JSON key.

classmethod custom_key(key: str) → Self

Return a JSON body component with a custom key.

A dot-separated key creates nested JSON objects.

Parameters:

key (str) – Key used in the JSON request body.

property depth: int

Return the number of levels in the custom JSON key.

property keys: list[str]

Return the custom JSON key split into nested key names.

class BodyForm

Bases: _BodyFileComponent

Mark a parameter as a field in a form request body.

File-like values, or fields whose metadata() configuration specifies a filename or content type, use multipart/form-data; other form fields default to URL encoding.

class Header

Bases: Component

Mark a parameter as an HTTP request header.

default_header() adds a static header to a decorated request.

static default_header(key: str, value: Any) → Callable[[_CallableT], _CallableT]

Add a static header to a decorated request.

Parameters:
  • key (str) – Header name.

  • value (Any) – Header value.

class Path

Bases: _UnsupportedCustomNameComponent

Mark a parameter as a placeholder in the request path.

The parameter name must match a str.format placeholder in path.

class Query

Bases: Component

Mark a parameter as an HTTP query-string value.

default_query() adds a static query parameter to a decorated request.

static default_query(key: str, value: Any) → Callable[[_CallableT], _CallableT]

Add a static query parameter to a decorated request.

Parameters:
  • key (str) – Query parameter name.

  • value (Any) – Query parameter value.

Request Core

class RequestCore

Base descriptor for a decorated HTTP request.

A request core is bound to a BaseSession instance when it is accessed as a session attribute. The bound request builds a backend-specific request from its static values and annotated function parameters, then executes the decorated function with any Response parameter filled in.

name

The name of the request.

Type:

str

func

The synchronous or asynchronous function executed after the response is received.

Type:

Callable[…, Any]

method

HTTP method.

Type:

str | Method

path

Path relative to the session base URL, unless the backend manages its own base URL.

Type:

str

directly_response

Return the response-pipeline result without executing the decorated function.

Type:

DirectResponseType | bool

raise_on

Raise HTTPException when the HTTP response status is not 200. 4xx and 5xx statuses use their matching concrete exception class when available.

Type:

bool

params

Static query parameters.

Type:

dict[str, Any]

headers

Static request headers.

Type:

dict[str, Any]

body

Static request body. Its encoding is determined by body_type.

Type:

Optional[Any]

header_parameter

Function parameters used as request headers.

Type:

dict[str, inspect.Parameter]

query_parameter

Function parameters used as query parameters.

Type:

dict[str, inspect.Parameter]

body_json_parameter

Function parameters collected into a JSON body.

Type:

dict[str, inspect.Parameter]

body_form_parameter

Function parameters collected into a form body.

Type:

dict[str, inspect.Parameter]

path_parameter

Function parameters substituted into the path.

Type:

dict[str, inspect.Parameter]

body_parameter

Metadata for the function parameter used as the complete request body.

Type:

Optional[BodyEntry]

body_parameter_type

Explicit body encoding, if one was inferred from the parameter annotations or form configuration.

Type:

Optional[BodyType]

response_parameter

Names of function parameters that receive the HTTP response.

Type:

list[str]

request_kwargs

Keyword arguments passed through to the backend request method.

Type:

dict[str, Any]

@before_hook

A decorator that registers a coroutine as a pre-invoke hook. A pre-invoke hook is called directly before the HTTP request is called.

This makes it a useful function to set up authorizations or any type of set up required.

Example

class GithubService(AsyncSession):
    def __init__(self, token: str):
        self.token = token
        super().__init__("https://api.github.com", aiohttp.ClientSession)

    @request("GET", "/users/{user}/repos")
    async def list_repositories(
        self, response: Response, user: Annotated[str, Path]
    ) -> list[dict[str, Any]]:
        return response.json()

    @list_repositories.before_hook
    async def authorization(self, req_obj: RequestCore, path: str):
        req_obj.headers["Authorization"] = f"Bearer: {self.token}"
        return req_obj, path
@after_hook

A decorator that registers a coroutine as a post-invoke hook. A post-invoke hook is called directly after the returned HTTP response.

This makes it a useful function to check correct response or any type of clean up response data.

Example

class GithubService(AsyncSession):
    def __init__(self):
        super().__init__("https://api.github.com", aiohttp.ClientSession)

    @request("GET", "/users/{user}/repos")
    async def list_repositories(
        self, response: Response, user: Annotated[str, Path]
    ) -> list[dict[str, Any]]:
        return response.json()

    @list_repositories.after_hook
    async def validation_status(self, response: Response):
        if response.status != 200:
            raise Exception("ERROR!")
        return response
copy() → Self

Creates a copy of this request.

Returns:

An independent request instance with copied static headers and query parameters.

Return type:

RequestCore

validation(parameter_name: str, index: int | None = None) → ValidationDecorator

Register a validator for a request function parameter.

The validator is called with (session, value) before the request is built. Its return value replaces the argument used in request components and in the decorated function.

Parameters:
  • index

  • parameter_name (str) – Name of a parameter in the decorated function signature.

Raises:

ValueError – If the parameter name is empty or does not exist in the request signature.

property body_type: BodyType | None

Return the body encoding selected for this request.

Return type:

Optional[BodyType]

property is_body: bool

Returns whether the HTTP request has a body element.

Return type:

bool

property is_formal_form: bool

Return whether this request has form parameters.

Return type:

bool

@request(method: str, path: str)

Decorate a session method as an HTTP request.

Accessing the decorated method on a Session or AsyncSession binds it to that session. Each invocation builds the request from static values and component parameters, then passes a Response to matching response parameters in the decorated function.

Parameters:
  • name (Optional[str]) – Request name; defaults to the decorated function name.

  • method (str | Method) – HTTP method.

  • path (str) – Path relative to the session base URL.

  • params (Optional[dict[str, Any]]) – Static query parameters.

  • headers (Optional[dict[str, Any]]) – Static request headers.

  • body (Optional[Any]) – Static request body.

  • directly_response (DirectResponseType | bool) – Return the response after hooks without executing the decorated function.

  • raise_on (bool) – Raise HTTPException when the HTTP response status is not 200. 4xx and 5xx statuses use their matching concrete exception class when available.

  • header_parameter (list[str]) – Legacy list of parameter names to use as headers.

  • query_parameter (list[str]) – Legacy list of parameter names to use as query parameters.

  • form_parameter (list[str]) – Legacy list of parameter names to use in a form body.

  • form_encoding (Optional[BodyFormEncoding]) – Encoding to use for form parameters. AUTO selects multipart when a file field is present, otherwise URL encoding.

  • body_json_parameter (list[str]) – Legacy list of parameter names to use in a JSON body.

  • path_parameter (list[str]) – Legacy list of parameter names substituted into path.

  • body_parameter (str) – Legacy parameter name to use as the complete body.

  • response_parameter (list[str]) – Legacy list of function parameter names that receive the response.

  • **request_kwargs

Warning

A complete Body parameter cannot be combined with BodyJson or BodyForm parameters.

@get(path: str)

Create a request decorator for the GET HTTP method.

All parameters have the same meaning as request().

@post(path: str)

Create a request decorator for the POST HTTP method.

All parameters have the same meaning as request().

@options(path: str)

Create a request decorator for the OPTIONS HTTP method.

All parameters have the same meaning as request().

@patch(path: str)

Create a request decorator for the PATCH HTTP method.

All parameters have the same meaning as request().

@put(path: str)

Create a request decorator for the PUT HTTP method.

All parameters have the same meaning as request().

@delete(path: str)

Create a request decorator for the DELETE HTTP method.

All parameters have the same meaning as request().

Same feature as ahttp_client.request.

Response

class Response

A common response wrapper for supported HTTP client libraries.

The wrapper exposes response information through a consistent interface and keeps the original response object available through raw.

Parameters:
  • response_obj (Any) – Original response object returned by the HTTP client library.

  • backend (BaseBackend) – Backend that provides response operations for response_obj.

  • deserializer (Optional[BaseDeserializer]) – Deserializer used to build model from this response. Left unset when the request has no @deserialize decorator applied.

async async_close() → None

Close the response from an async pipeline.

Some asynchronous clients, including aiohttp, expose a synchronous response close method. The async wrapper accepts both backend styles so callers do not need backend-specific cleanup branches.

close() → None

Close the underlying HTTP response.

content() → bytes

Return the response body as bytes.

json(json_parser: Callable[..., Any] | None = None, json_kwargs: dict[str, Any] | None = None) → Any

Parse the response body as JSON.

Parameters:
  • json_parser (Optional[Callable[..., Any]]) – Custom JSON parser. The backend default parser is used when empty.

  • json_kwargs (Optional[dict[str, Any]]) – Keyword arguments passed to json_parser or the backend parser.

raise_for_status() → None

Raise the exception matching this response’s 4xx or 5xx status.

Unknown statuses in either error range raise HTTPClientError or HTTPServerError respectively. Other status codes return without raising an exception.

text() → str

Return the response body decoded as text.

property closed: bool

Return whether the response has been closed.

property header: dict[str, Any]

Return response headers as a dictionary.

property model: ModelT | list[ModelT] | None

Return the response body deserialized into a model instance.

Returns None when no deserializer was attached to the request (that is, no @deserialize decorator was applied). See Serialization for how a deserializer gets attached.

property raw: Any

Return the original response object from the HTTP client library.

property session: Any

Return the original HTTP client session that created this response.

property status: int

Return the HTTP response status code.

property url: str

Return the URL of the HTTP response.

Session

class AsyncSession

A session for asynchronous requests.

Supported client classes are aiohttp.ClientSession and httpx.AsyncClient. Decorated coroutine methods are bound to this session and executed with the configured base URL.

Parameters:
  • base_url (str) – Base URL used for request paths.

  • session (type) – Supported asynchronous HTTP client session class.

  • directly_response (DirectResponseType | bool) – Return the response-pipeline result instead of executing decorated request functions.

  • **kwargs – Keyword arguments passed to the HTTP client session constructor.

@single_session(base_url: str, session: type, **session_kwargs)

A single session for one request.

Parameters:
  • base_url (str) – base url of the API.

  • session (type) – HTTP session class used for processing requests.

  • session_kwargs – Keyword arguments passed to the HTTP session class.

Example

The session is defined through the function’s decoration.

@AsyncSession.single_session("https://api.yhs.kr", aiohttp.ClientSession)
@request("GET", "/bus/station")
async def station_query(
    session: AsyncSession, name: Query | str
) -> Response:
    pass
async after_request(response: Any) → Any

Run after the backend receives a response and before a request hook.

Override this method to transform the Response for every request made by this session.

Parameters:

response (Any) – Response returned by the backend.

Returns:

Value passed to the request-level post-hook or decorated function.

Return type:

Any

async before_request(request: RequestCore[Any, Any], path: str) → tuple[RequestCore[Any, Any], str]

Run after a request-level pre-hook and before dispatching the request.

Override this method to alter the request object or final path for all requests made by this session.

Parameters:
  • request (RequestCore) – Request descriptor prepared for this invocation.

  • path (str) – Request path after path parameters have been substituted.

Returns:

Request descriptor and path to dispatch.

Return type:

tuple[RequestCore, str]

async close() → None

Close the underlying asynchronous HTTP client session.

async delete(path: str, **kwargs: Any) → Any

Make a raw asynchronous DELETE request.

async get(path: str, **kwargs: Any) → Any

Make a raw asynchronous GET request.

async options(path: str, **kwargs: Any) → Any

Make a raw asynchronous OPTIONS request.

async patch(path: str, **kwargs: Any) → Any

Make a raw asynchronous PATCH request.

async post(path: str, **kwargs: Any) → Any

Make a raw asynchronous POST request.

async put(path: str, **kwargs: Any) → Any

Make a raw asynchronous PUT request.

async request(method: str, path: str, **kwargs: Any) → Any

Make a raw asynchronous HTTP request.

path is joined with the base URL when required. Keyword arguments are passed directly to the underlying HTTP client.

property backend: AsyncBackend

Create the asynchronous backend lazily inside the running loop.

property closed: bool

Return whether the underlying HTTP client session is closed.

See also

This page covers the core request/component/session API. The backend adapter classes have their own page at Backend, retry configuration at Retry, the serializer/deserializer classes at Serialization, and the HTTP exception hierarchy at Exception.