lback.api package
This file serves as the initialization point for the ‘lback_framework/lback/api’ package. It is designed to expose the core components necessary for building robust RESTful APIs within the Lback web framework. This package centralizes the definition and management of API functionalities, including views, serializers, mixins, and documentation tools.
—
Key Components Exposed by this Package:
APIDocs: Manages and generates comprehensive API documentation for the Lback framework. This component is crucial for creating structured and interactive documentation (e.g., OpenAPI/Swagger specifications) that details all available API endpoints, their expected request formats, and their response structures. It aids developers in understanding and integrating with Lback-powered APIs by providing metadata like API title, version, and description, and can register endpoints for automatic documentation generation.
Generic API Views (from .generics): A suite of pre-built, reusable classes designed to handle common RESTful operations (CRUD - Create, Read, Update, Delete) with minimal boilerplate code. These views abstract away repetitive logic, allowing for rapid API development.
- GenericAPIView: The foundational class for all generic API views, providing core mechanisms for
handling HTTP requests, interacting with serializers, and managing querysets.
- ListAPIView: Designed for retrieving collections of resources, handling HTTP GET requests
for listing multiple instances of a model, often with pagination and filtering support.
- CreateAPIView: Handles HTTP POST requests for creating new resources, deserializing incoming data,
validating it, and saving new model instances.
- RetrieveAPIView: Processes HTTP GET requests for fetching a single resource instance,
typically identified by a primary key or unique identifier.
- UpdateAPIView: Supports HTTP PUT (full update) and PATCH (partial update) requests for
modifying existing resources.
DestroyAPIView: Handles HTTP DELETE requests for removing existing resource instances.
- ListCreateAPIView: A composite view combining listing (GET) and creation (POST) functionalities
on the same endpoint.
- RetrieveUpdateDestroyAPIView: A comprehensive view for single-resource management,
combining retrieval (GET), updating (PUT/PATCH), and deletion (DELETE).
Mixins (from .mixins): Reusable classes that provide specific behaviors to generic views, allowing for flexible composition of API functionalities. These mixins encapsulate common logic for model operations.
ListModelMixin: Provides logic for listing a queryset of model instances.
CreateModelMixin: Provides logic for creating a new model instance.
RetrieveModelMixin: Provides logic for retrieving a single model instance.
UpdateModelMixin: Provides logic for updating an existing model instance.
DestroyModelMixin: Provides logic for deleting a model instance.
Serializers (from .serializer): Essential components for data serialization and deserialization. They are crucial for converting complex data types (like model instances) into formats suitable for API responses (e.g., JSON) and converting incoming data back into model instances for processing.
- Field: The base class for all serializer fields, defining common behavior for data representation,
validation, and conversion.
BooleanField: A serializer field for handling boolean values.
- BaseModelSerializer: The base serializer class designed for integration with Lback’s models,
simplifying conversion between model instances and serializable data structures.
IntegerField: A serializer field for handling integer numbers.
StringField: A serializer field for handling text-based data (strings).
RelatedField: A serializer field for representing relationships between different models.
- DateTimeField: A serializer field for handling date and time values, managing conversion
to and from various string formats.
View Classes (from .view): Fundamental view classes that serve as the entry points for handling web requests within the Lback framework.
- APIView: The primary base class for defining API views, providing a robust foundation for handling
different HTTP methods and orchestrating the request-response cycle for API endpoints.
- BaseView: A more general-purpose base view class that might serve as a fundamental building block
for views not strictly adhering to REST principles, or for traditional web page rendering.
Submodules
lback.api.docs module
- class lback.api.docs.APIDocs(router: Router, title: str = 'Lback API', version: str = '1.0.0', description: str = 'API Documentation')[source][source]
Bases:
objectGenerates OpenAPI (Swagger) documentation for the Lback API. Aims to automatically collect documentation details from registered routes and views. Integrates SignalDispatcher to emit events during the documentation generation process.
- __init__(router: Router, title: str = 'Lback API', version: str = '1.0.0', description: str = 'API Documentation')[source][source]
Intializes the APIDocs generator. Emits ‘api_docs_initialized’ signal.
- Parameters:
router – The framework’s central Router instance.
title – The title of the API documentation.
version – The version of the API.
description – A description of the API.
- collect_documentation()[source][source]
Collects documentation details from the registered routes and views. This method orchestrates the automatic documentation generation. Emits ‘api_docs_collection_started’ and ‘api_docs_collection_finished’ signals.
- generate_openapi() Dict[str, Any][source][source]
Generates the full OpenAPI specification dictionary. Emits ‘openapi_spec_generated’ signal.
- register_serializer_schema(serializer_class: Type[BaseModelSerializer], schema_name: str)[source][source]
Generates an OpenAPI schema from a BaseModelSerializer and adds it to components. This implementation will inspect the serializer fields to build the schema.
lback.api.generics module
- class lback.api.generics.CreateAPIView[source][source]
Bases:
CreateModelMixin,GenericAPIViewView for creating a model instance.
- class lback.api.generics.DestroyAPIView[source][source]
Bases:
DestroyModelMixin,GenericAPIViewView for deleting a model instance.
- class lback.api.generics.GenericAPIView[source][source]
Bases:
APIViewBase class for all generic views. Provides context for various generic behaviors.
- class lback.api.generics.ListAPIView[source][source]
Bases:
ListModelMixin,GenericAPIViewView for listing a queryset.
- class lback.api.generics.ListCreateAPIView[source][source]
Bases:
ListModelMixin,CreateModelMixin,GenericAPIViewView for listing and creating model instances.
- class lback.api.generics.RetrieveAPIView[source][source]
Bases:
RetrieveModelMixin,GenericAPIViewView for retrieving a model instance.
- class lback.api.generics.RetrieveUpdateDestroyAPIView[source][source]
Bases:
RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIViewView for retrieving, updating, and deleting a model instance.
lback.api.mixins module
- class lback.api.mixins.CreateModelMixin[source][source]
Bases:
objectMixins لـ Create API: Handles creating a new object. Requires the view to have model and serializer_class defined.
- class lback.api.mixins.DestroyModelMixin[source][source]
Bases:
objectMixins لـ Destroy API: Handles deleting an existing object. Requires the view to have model defined.
- class lback.api.mixins.ListModelMixin[source][source]
Bases:
objectMixins لـ List API: Handles listing a queryset of objects. Requires the view to have model and serializer_class defined.
lback.api.serializer module
- class lback.api.serializer.BaseModelSerializer(instance: Any = None, data: Dict[str, Any] | None = None, many: bool = False, partial: bool = False, context: Dict[str, Any] | None = None)[source][source]
Bases:
objectBase serializer class for converting model instances to dictionaries and validating/converting dictionaries to model instances. Integrates SignalDispatcher to emit events during serialization, validation, and saving.
- class Meta[source][source]
Bases:
objectInner class for serializer options.
- exclude: List[str] = []
- extra_kwargs: Dict[str, Dict[str, Any]] = {}
- fields: List[str] | str = '__all__'
- read_only_fields: List[str] = []
- property data: Dict[str, Any] | List[Dict[str, Any]]
- property errors: Dict[str, List[str]]
- property is_valid: bool
- save(session: Any) Any[source][source]
Creates or updates a model instance using validated data. Requires a database session. Emits ‘serializer_pre_save’ and ‘serializer_post_save’ signals.
- Parameters:
session – The database session to use for saving.
- Returns:
The created or updated model instance.
- Raises:
ValidationError – If the data is not valid.
RuntimeError – If validated data is missing unexpectedly.
NotImplementedError – If the serializer has no associated model_class.
Exception – For other unexpected errors during the save process.
- property validated_data: Dict[str, Any] | None
- class lback.api.serializer.BooleanField(required: bool = True, allow_null: bool = False, default: Any = None, help_text: str | None = None, read_only: bool = False)[source][source]
Bases:
Field- property openapi_type: Dict[str, Any]
- class lback.api.serializer.DateTimeField(format: str | None = None, **kwargs)[source][source]
Bases:
FieldA field for handling datetime objects, converting them to/from ISO 8601 strings.
- property openapi_type: Dict[str, Any]
- to_internal_value(data: Any) datetime | None[source][source]
Converts input data to its internal value for validation/saving.
- class lback.api.serializer.Field(required: bool = True, allow_null: bool = False, default: Any = None, help_text: str | None = None, read_only: bool = False)[source][source]
Bases:
objectBase class for serializer fields. Provides methods for data representation, internal value conversion, and validation.
- __set_name__(owner, name)[source][source]
Called automatically by Python when the field is defined on a class.
- to_internal_value(data: Any) Any[source][source]
Converts input data to its internal value for validation/saving.
- class lback.api.serializer.IntegerField(min_value: int | None = None, max_value: int | None = None, **kwargs)[source][source]
Bases:
Field- property openapi_type: Dict[str, Any]
- class lback.api.serializer.RelatedField(serializer_class: Type[BaseModelSerializer], many: bool = False, **kwargs)[source][source]
Bases:
FieldA field for handling relationships to other models. Can represent as primary key or nested serializer.
- property openapi_type: Dict[str, Any]
lback.api.view module
- class lback.api.view.APIView[source][source]
Bases:
BaseViewBase class for API views, providing common functionalities like: - Default allowed HTTP methods. - Automatic request body parsing (JSON). - Automatic response serialization to JSON. - Basic object/queryset retrieval logic (requires model and serializer_class). - Standardized error responses.
- dispatch(request: Any, *args, **kwargs) Response[source][source]
Dispatches the incoming request to the appropriate HTTP method handler. Emits ‘view_dispatch_started’, ‘view_dispatch_succeeded’, ‘view_method_not_allowed’, or ‘view_handler_not_implemented’ signals.
- Parameters:
request – The incoming request object (already processed by middleware).
*args – Positional arguments extracted from the URL path.
**kwargs – Keyword arguments extracted from the URL path.
- Returns:
The result of calling the specific method handler (e.g., self.get, self.post). This result is typically a Response object or data to be converted to a Response.
- Raises:
MethodNotAllowed – If the request method is not in self.methods. (Although the Router should ideally catch this first).
NotImplementedError – If a method is allowed but no handler method is defined.
Any exception raised by the specific method handler. –
- get_object()[source][source]
Retrieves a single object based on the ID provided in the URL kwargs.
- Returns:
The model instance corresponding to the provided primary key.
- Return type:
Any
- Raises:
NotFound – If the primary key is not found in the URL or the object does not exist.
- get_queryset()[source][source]
Returns the base QuerySet for the specified model.
- Returns:
The QuerySet for the model.
- Return type:
QuerySet
- Raises:
NotImplementedError – If model is not defined.
Exception – If the database session is not available.
- get_serializer(instance: Any = None, data: Dict[str, Any] | None = None, **kwargs) BaseModelSerializer[source][source]
Returns an instance of the serializer specified for this view.
- Parameters:
instance (Any, optional) – The model instance to serialize.
data (dict, optional) – Data to be deserialized and validated.
**kwargs – Additional keyword arguments for the serializer.
- Returns:
An instance of the serializer class.
- Return type:
- Raises:
NotImplementedError – If serializer_class is not defined.
- methods: List[str] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']
- serializer_class: Type[BaseModelSerializer] | None = None
- class lback.api.view.BaseView[source][source]
Bases:
objectBase class for all view handlers in the framework. Provides basic dispatching logic. Integrates SignalDispatcher to emit events during request dispatching.
- dispatch(request: Any, *args, **kwargs) Any[source][source]
Dispatches the incoming request to the appropriate HTTP method handler. Emits ‘view_dispatch_started’, ‘view_dispatch_succeeded’, ‘view_method_not_allowed’, or ‘view_handler_not_implemented’ signals.
- Parameters:
request – The incoming request object (already processed by middleware).
*args – Positional arguments extracted from the URL path.
**kwargs – Keyword arguments extracted from the URL path.
- Returns:
The result of calling the specific method handler (e.g., self.get, self.post). This result is typically a Response object or data to be converted to a Response.
- Raises:
MethodNotAllowed – If the request method is not in self.methods. (Although the Router should ideally catch this first).
NotImplementedError – If a method is allowed but no handler method is defined.
Any exception raised by the specific method handler. –
- methods: List[str] | None = None