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.
- 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
PathorBody.
- 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,_UnsupportedCustomNameComponentMark a parameter as the complete request body.
dict,list, andtuplevalues are encoded as JSON; other values (including file-like values) are sent as raw body data. ABodyparameter cannot be combined withBodyJsonorBodyFormparameters.metadata()adds filename and content-type metadata without changing the raw-body encoding.
- class BodyJson¶
Bases:
ComponentMark a parameter as a field in a JSON request body.
Use
custom_key()to place the value under a different or nested JSON key.
- class BodyForm¶
Bases:
_BodyFileComponentMark a parameter as a field in a form request body.
File-like values, or fields whose
metadata()configuration specifies a filename or content type, usemultipart/form-data; other form fields default to URL encoding.
- class Header¶
Bases:
ComponentMark a parameter as an HTTP request header.
default_header()adds a static header to a decorated request.
- class Path¶
Bases:
_UnsupportedCustomNameComponentMark a parameter as a placeholder in the request path.
The parameter name must match a
str.formatplaceholder inpath.
- class Query¶
Bases:
ComponentMark a parameter as an HTTP query-string value.
default_query()adds a static query parameter to a decorated request.
Request Core¶
- class RequestCore¶
Base descriptor for a decorated HTTP request.
A request core is bound to a
BaseSessioninstance 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 anyResponseparameter filled in.- func¶
The synchronous or asynchronous function executed after the response is received.
- Type:
Callable[…, Any]
- directly_response¶
Return the response-pipeline result without executing the decorated function.
- Type:
DirectResponseType | bool
- raise_on¶
Raise
HTTPExceptionwhen the HTTP response status is not200. 4xx and 5xx statuses use their matching concrete exception class when available.- Type:
- body¶
Static request body. Its encoding is determined by
body_type.- Type:
Optional[Any]
- header_parameter¶
Function parameters used as request headers.
- Type:
- query_parameter¶
Function parameters used as query parameters.
- Type:
- body_json_parameter¶
Function parameters collected into a JSON body.
- Type:
- body_form_parameter¶
Function parameters collected into a form body.
- Type:
- path_parameter¶
Function parameters substituted into the path.
- Type:
- 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]
- request_kwargs¶
Keyword arguments passed through to the backend request method.
- @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:
- 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.
- @request(method: str, path: str)¶
Decorate a session method as an HTTP request.
Accessing the decorated method on a
SessionorAsyncSessionbinds it to that session. Each invocation builds the request from static values and component parameters, then passes aResponseto 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
HTTPExceptionwhen the HTTP response status is not200. 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.
AUTOselects 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
Bodyparameter cannot be combined withBodyJsonorBodyFormparameters.
- @get(path: str)¶
Create a request decorator for the
GETHTTP method.All parameters have the same meaning as
request().
- @post(path: str)¶
Create a request decorator for the
POSTHTTP method.All parameters have the same meaning as
request().
- @options(path: str)¶
Create a request decorator for the
OPTIONSHTTP method.All parameters have the same meaning as
request().
- @patch(path: str)¶
Create a request decorator for the
PATCHHTTP method.All parameters have the same meaning as
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
modelfrom this response. Left unset when the request has no@deserializedecorator applied.
- async async_close() None¶
Close the response from an async pipeline.
Some asynchronous clients, including aiohttp, expose a synchronous response
closemethod. The async wrapper accepts both backend styles so callers do not need backend-specific cleanup branches.
- json(json_parser: Callable[..., Any] | None = None, json_kwargs: dict[str, Any] | None = None) Any¶
Parse the response body as JSON.
- raise_for_status() None¶
Raise the exception matching this response’s 4xx or 5xx status.
Unknown statuses in either error range raise
HTTPClientErrororHTTPServerErrorrespectively. Other status codes return without raising an exception.
- property model: ModelT | list[ModelT] | None¶
Return the response body deserialized into a model instance.
Returns
Nonewhen no deserializer was attached to the request (that is, no@deserializedecorator was applied). See Serialization for how a deserializer gets attached.
Session¶
- class AsyncSession¶
A session for asynchronous requests.
Supported client classes are
aiohttp.ClientSessionandhttpx.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:
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
Responsefor 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:
- async request(method: str, path: str, **kwargs: Any) Any¶
Make a raw asynchronous HTTP request.
pathis 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.
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.