This documentation provides a comprehensive guide to using nexios-generic built on top of Nexios, a lightweight Python web framework. The framework is designed to simplify the creation of CRUD (Create, Read, Update, Delete) APIs using Tortoise ORM for database management and Pydantic for data validation. While this framework is a side project and not extensively tested, it provides a solid foundation for building APIs quickly and efficiently.
Table of Contents
Core Components
GenericAPIView
The GenericAPIView class is the base class for all views in the framework. It provides the foundational logic for handling requests, validating data, and formatting responses. Key methods include:
get_queryset(): Returns the queryset for the view.get_pydantic_class(): Returns the Pydantic model class used for data validation and serialization.validate_request(): Validates the incoming request data using the Pydantic model.get_object(): Retrieves a single object from the database based on the lookup field.format_error_response(): Formats an error response with a status code and details.format_success_response(): Formats a success response with data and a status code.
Mixins
Mixins provide reusable functionality for common CRUD operations. They are designed to be combined with GenericAPIView to create views with specific behavior.
CreateModelMixin: Handles creating new objects.RetrieveModelMixin: Handles retrieving a single object.ListModelMixin: Handles listing multiple objects.UpdateModelMixin: Handles updating existing objects.DeleteModelMixin: Handles deleting objects.
Views
The framework provides pre-built views that combine the mixins for common use cases:
ListCreateAPIView: CombinesListModelMixinandCreateModelMixinfor listing and creating objects.RetrieveUpdateDestroyAPIView: CombinesRetrieveModelMixin,UpdateModelMixin, andDeleteModelMixinfor retrieving, updating, and deleting objects.ListCreateRetrieveUpdateDestroyAPIView: Combines all mixins for full CRUD functionality.
Getting Started
Installation
Before using the framework, ensure you have the following installed:
- Python 3.7 or higher
- Nexios (a lightweight Python web framework)
- Tortoise ORM (for database management)
- Pydantic (for data validation)
You can install the required packages using pip:
pip install nexios tortoise-orm pydantic
Project Setup
- Initialize Nexios: Create a new Nexios application.
- Configure Tortoise ORM: Set up your database configuration.
- Define Models: Create your database models using Tortoise ORM.
- Define Pydantic Schemas: Create Pydantic schemas for data validation and serialization.
- Create Views: Use the provided mixins and views to create your API endpoints.
- Add Routes: Add your views as routes in your Nexios application.
Usage Guide
Defining Models
Define your database models using Tortoise ORM. For example, a User model:
from tortoise import fields, models
class User(models.Model):
id = fields.IntField(pk=True)
username = fields.CharField(max_length=50, unique=True)
email = fields.CharField(max_length=100, unique=True)
class Meta:
table = "users"
Defining Pydantic Schemas
Define Pydantic schemas for data validation and serialization. For example, a UserSchema:
from pydantic import BaseModel
class UserSchema(BaseModel):
id: int | None = None
username: str
email: str
class Config:
from_attributes = True
Creating Views
Use the provided mixins and views to create your API endpoints. For example, to create a view for listing and creating users:
from src.views import ListCreateAPIView
from src.base import GenericAPIView
class UserView(ListCreateAPIView):
pydantic_class = UserSchema
async def get_queryset(self):
return User.all()
Adding Routes
Add your views as routes in your Nexios application:
from nexios import get_application
app = get_application()
app.add_route(UserView.as_route("/users"))
Advanced Usage
Customizing Querysets
You can customize the queryset used by your views by overriding the get_queryset() method. For example, to filter users by a specific condition:
class UserView(ListCreateAPIView):
pydantic_class = UserSchema
async def get_queryset(self):
return User.filter(username__icontains="admin")
Customizing Validation
You can customize the validation logic by overriding the validate_request() method. For example, to add custom validation rules:
class UserView(ListCreateAPIView):
pydantic_class = UserSchema
async def validate_request(self):
data = await self.request.json()
if "username" not in data:
raise ValueError("Username is required")
return self.pydantic_class(**data)
Error Handling
You can customize error handling by overriding the error-handling methods in the mixins. For example, to customize the error response format:
class UserView(ListCreateAPIView):
pydantic_class = UserSchema
def handle_validation_error(self, res, error):
return res.status(400).json({"error": "Validation failed", "details": str(error)})
Extending Mixins
You can extend the mixins to add custom behavior. For example, to add logging to the CreateModelMixin:
class LoggingCreateMixin(CreateModelMixin):
async def perform_create(self, instance):
print(f"Creating object: {instance}")
return await super().perform_create(instance)
Example Project
Here’s a complete example of a simple API for managing users:
from tortoise import fields, models
from pydantic import BaseModel
from src.views import ListCreateAPIView
from nexios import get_application
# Define the User model
class User(models.Model):
id = fields.IntField(pk=True)
username = fields.CharField(max_length=50, unique=True)
email = fields.CharField(max_length=100, unique=True)
class Meta:
table = "users"
# Define the Pydantic schema
class UserSchema(BaseModel):
id: int | None = None
username: str
email: str
class Config:
from_attributes = True
# Create the view
class UserView(ListCreateAPIView):
pydantic_class = UserSchema
async def get_queryset(self):
return User.all()
# Add the route to Nexios
app = get_application()
app.add_route(UserView.as_route("/users"))
Conclusion
This framework provides a lightweight and easy-to-use solution for building CRUD APIs with Nexios, Tortoise ORM, and Pydantic. While it is not extensively tested, it offers a solid foundation for quickly creating APIs. Feel free to extend and modify the framework to suit your needs!
For more information on Nexios, visit the official documentation: Nexios Documentation.
GitHub Badges
Logo
Thank you for using this framework! If you have any questions or feedback, please open an issue on GitHub.
Metadata
Release files for nexios-generic 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| nexios_generic-0.1.1.tar.gz | 5.6 kB | Without provenance | Details for nexios_generic-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| nexios_generic-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for nexios_generic-0.1.1-py3-none-any.whl |
Total release size: 12.0 kB
Release files / nexios_generic-0.1.1.tar.gz
| Download URL | nexios_generic-0.1.1.tar.gz |
|---|---|
| Size | 5.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
35e515ddca45df1749aad994bd56ecfcc57f6e3f331cdac46272f40dc7bebd6c
|
|
BLAKE2b-256 checksum How to use checksums |
00590fe705bac13f7684cf90d7733473258726ffe5bd6c232cce9e6bc0941575
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.1.1 CPython/3.13.2 Windows/10
|
Release files / nexios_generic-0.1.1-py3-none-any.whl
| Download URL | nexios_generic-0.1.1-py3-none-any.whl |
|---|---|
| Size | 6.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
07629e03bb9a50e287a288921daa50bcd81116d219e1f25137a21ee6b4623ece
|
|
BLAKE2b-256 checksum How to use checksums |
ad743933c1454294dcc85670bb356d0dea77e19e912045fc6e1df9f862fa4b8d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.1.1 CPython/3.13.2 Windows/10
|
Security for nexios-generic 0.1.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.