| Crates.io | reinhardt-rest |
| lib.rs | reinhardt-rest |
| version | 0.1.0-alpha.2 |
| created_at | 2026-01-23 05:54:59.928721+00 |
| updated_at | 2026-01-23 06:29:28.874283+00 |
| description | REST API framework aggregator for Reinhardt |
| homepage | |
| repository | https://github.com/kent8192/reinhardt-rs |
| max_upload_size | |
| id | 2063567 |
| size | 1,270,886 |
Export-only integration layer for Reinhardt REST API framework.
This crate serves as a convenience layer that combines multiple Reinhardt crates into a single import. It does not contain its own implementation or tests - all functionality is provided by the underlying specialized crates.
Add reinhardt to your Cargo.toml:
[dependencies]
reinhardt = { version = "0.1.0-alpha.1", features = ["rest"] }
# Or use a preset:
# reinhardt = { version = "0.1.0-alpha.1", features = ["standard"] } # Recommended
# reinhardt = { version = "0.1.0-alpha.1", features = ["full"] } # All features
Then import REST features:
use reinhardt::rest::{ApiResponse, ResponseBuilder, IntoApiResponse};
use reinhardt::rest::{JwtAuth, IsAuthenticated, AllowAny, User, SimpleUser};
use reinhardt::rest::{DefaultRouter, Router, Route};
use reinhardt::rest::{PaginatedResponse};
Note: REST features are included in the standard and full feature presets.
reinhardt-auth)JwtAuth - JWT authentication backendClaims - JWT claims structureUser - Base user traitSimpleUser - Simple user implementationAnonymousUser - Unauthenticated user representationAllowAny - Allow all users (authenticated or not)IsAuthenticated - Require authenticationIsAuthenticatedOrReadOnly - Read-only for anonymous, full access for authenticatedIsAdminUser - Require admin privilegesAuthResult<U> - Result type for authentication operationsAuthBackend - Authentication backend traitreinhardt-routers)DefaultRouter - Default router with automatic ViewSet URL generationRouter - Base router traitRoute - Individual route definitionUrlPattern - URL pattern matchingreinhardt-browsable-api)ApiResponse<T> - DRF-style API response wrapper
success, success_with_status)error, validation_error)not_found, unauthorized, forbidden)ResponseBuilder<T> - Fluent builder for API responsesIntoApiResponse<T> - Trait for converting types to API responsesPaginatedResponse - Paginated response wrapper (from reinhardt-pagination)reinhardt-openapi)OpenApiSchema - OpenAPI 3.0 schema generationComponents - Reusable schema componentsOperation - API operation definitionsParameter - Request parameter definitionsServer - Server configurationSwaggerUI - Interactive API documentationreinhardt-pagination)PageNumberPagination - Page-based paginationLimitOffsetPagination - Offset-based paginationCursorPagination - Cursor-based paginationreinhardt-filters)SearchFilter - Search across multiple fieldsOrderingFilter - Sort results by fieldsQueryFilter - Type-safe query filteringMultiTermSearch - Multi-term search operationsreinhardt-throttling)AnonRateThrottle - Rate limiting for anonymous usersUserRateThrottle - Rate limiting for authenticated usersScopedRateThrottle - Per-endpoint rate limitingreinhardt-signals)pre_save, post_save - Model save signalspre_delete, post_delete - Model delete signalsm2m_changed - Many-to-many relationship signalsThis crate does not contain tests. All functionality is tested in the underlying specialized crates:
reinhardt-auth/tests/reinhardt-routers/tests/reinhardt-browsable-api/tests/src/response.rstests/integration/use reinhardt::rest::{
// Authentication
JwtAuth, IsAuthenticated, AllowAny, User, SimpleUser,
// Routing
DefaultRouter, Router, Route,
// Response handling
ApiResponse, ResponseBuilder, IntoApiResponse,
// Pagination
PaginatedResponse,
};
// Create a successful response
let user = SimpleUser::new(1, "Alice");
let response = ApiResponse::success(user);
// Build a custom response
let response = ResponseBuilder::new()
.data("Success")
.status(201)
.message("Resource created")
.build();
// Convert Result to ApiResponse
let result: Result<String, String> = Ok("data".to_string());
let response = result.into_api_response();
HTTP method badges with color coding (GET, POST, PUT, PATCH, DELETE)
Monospace endpoint display
Dark theme code blocks for JSON responses
Responsive container layout with shadow effects
Form styling with proper input controls
Header table display with clean formatting
utoipa re-exports
OpenApiSchema (utoipa's OpenApi type)utoipa-swagger-ui
/api/openapi.jsonserde_yaml dependency (capability present in dependencies)ToSchema Trait: Core trait for types that can generate OpenAPI schemas
schema() method returns OpenAPI schema representationschema_name() method returns optional schema identifierOption<T> and Vec<T>Schema Derive Macro: #[derive(Schema)] procedural macro for automatic schema generation
Option<T> fields are optional)#[schema(example = "...", description = "...")]$ref references#[serde(rename)], #[serde(skip)])HashMap<K,V> schema generationIntrospect ViewSet methods and serializers
Generate paths and operations from ViewSet definitions
Extract parameter information from method signatures
Automatic request/response schema generation from serializers
Serializer trait: Generic trait for data serialization and deserialization
serialize(): Convert Rust types to output formatdeserialize(): Parse output format back to Rust typesSerializerError: Type-safe error handling for serialization failuresJsonSerializer<T>: JSON serialization implementation
serde_json for efficient JSON handlingSerialize and DeserializeDeserializer trait: Dedicated deserialization interface
ModelSerializer<M>: Automatic serialization for ORM models
validate() methodreinhardt-orm::Model traitMetaConfig: Django REST Framework-style Meta options
fields: Explicitly include specific fieldsexclude: Exclude specific fieldsread_only_fields: Mark fields as read-onlywrite_only_fields: Mark fields as write-only (e.g., passwords)FieldIntrospector: Automatic field discovery and type inference
FieldInfo (name, type, optional, collection, primary key)field_names(), required_fields(), optional_fields(), primary_key_field()TypeMapper for common Rust typesFieldInfo: Rich field metadata
NestedSerializerConfig: Configure nested object serialization
allow_create, allow_update)NestedFieldConfig: Individual nested field configuration
depth(): Set nesting depth (default: 1)read_only(): Mark as read-onlywritable(): Enable create/update operationsallow_create(), allow_update(): Fine-grained permissionsSerializationContext: Circular reference and depth management
RecursiveError: Error handling for nested serialization
MaxDepthExceeded: Nesting too deepCircularReference: Circular dependency detectedSerializationError: Generic serialization failuresValidatorConfig<M>: Manage validators for ModelSerializer
UniqueValidator and UniqueTogetherValidatorUniqueValidator<M>: Enforce field uniqueness in database
with_message() for custom error messagesUniqueTogetherValidator<M>: Ensure unique field combinations
with_message()SerializerError: Comprehensive error type for all serialization operations
Validation(ValidatorError): Validation errors with detailed contextSerde { message }: Serialization/deserialization errorsOther { message }: Generic errorsunique_violation(), unique_together_violation(), required_field(), database_error()is_validation_error(), as_validator_error() for error inspectionValidatorError: Detailed validation error information
UniqueViolation: Single field uniqueness violationUniqueTogetherViolation: Multi-field uniqueness violationRequiredField: Missing required fieldFieldValidation: Field constraint violation (regex, range, etc.)DatabaseError: Database operation errorsCustom: Generic validation errorsmessage(), field_names(), is_database_error(), is_uniqueness_violation()ContentNegotiator: Select appropriate response format based on client requestMediaType: Parse and compare media type stringsreinhardt-parsers)JSONParser: Parse JSON request bodiesFormParser: Parse form-encoded dataMultiPartParser: Handle multipart/form-data (file uploads)FileUploadParser: Direct file upload handlingParseError: Error type for parsing failuresFieldError: Comprehensive error types for field validation failures
CharField: String field with length validation
min_length(), max_length(), required(), allow_blank()IntegerField: Integer field with range validation
min_value(), max_value(), required(), allow_null()FloatField: Floating-point field with range validation
min_value(), max_value(), required(), allow_null()BooleanField: Boolean field handling
required(), allow_null(), default()EmailField: Email format validation
required(), allow_blank(), allow_null()URLField: URL format validation
required(), allow_blank(), allow_null()ChoiceField: Enumerated value validation
required(), allow_blank(), allow_null()SerializerMethodField: Compute custom read-only fields
.method_name()read_only: true)full_name field computed from first_name + last_nameMethodFieldProvider trait: Support for serializers with method fields
compute_method_fields(): Generate all method field valuescompute_method(): Generate single method field valueMethodFieldRegistry: Manage multiple method fields
.register().get() and .contains().all()ValidationError: Structured validation error messages
FieldError: Single field validation errors with field name and messageMultipleErrors: Collection of multiple validation errorsObjectError: Object-level validation errorsfield_error(), object_error(), multiple()FieldValidator trait: Field-level validation
validate(): Validate individual field valuesObjectValidator trait: Object-level validation
validate(): Validate entire objects with multiple fieldsFieldLevelValidation trait: Serializer field-level validation
validate_field(): Validate specific field by nameget_field_validators(): Get all registered field validatorsvalidate_<field>() pattern supportObjectLevelValidation trait: Serializer object-level validation
validate(): Validate entire serialized objectvalidate_fields() helper: Validate all fields in a data object
use reinhardt::rest::serializers::HyperlinkedModelSerializer;
let serializer = HyperlinkedModelSerializer::<User>::new("user-detail", None);
// Generates URLs like: {"url": "/api/users/123/", "username": "alice"}
// When using UrlReverser
// let reverser: Arc<dyn UrlReverser> = Arc::new(MyUrlReverser);
// let serializer = HyperlinkedModelSerializer::<User>::new("user-detail", Some(reverser));
use reinhardt::rest::serializers::NestedSerializer;
let serializer = NestedSerializer::<Post, User>::new("author", 2);
// Serializes: {"title": "Post", "author": {"id": 1, "username": "alice"}}
use reinhardt::rest::serializers::{PrimaryKeyRelatedField, SlugRelatedField};
// Primary key relation: {"author": 123}
let pk_field = PrimaryKeyRelatedField::<User>::new();
// Slug relation: {"author": "alice-smith"}
let slug_field = SlugRelatedField::<User>::new("slug");
SerializerSaveMixin trait: Django-style save interface for serializersSaveContext: Transaction-aware context for save operationsuse reinhardt::rest::serializers::{SerializerSaveMixin, SaveContext};
use reinhardt::db::orm::{Model, Manager};
// Create new instance
let context = SaveContext::new();
let user = serializer.save(context).await?;
// Update existing instance
let context = SaveContext::with_instance(existing_user);
let updated_user = serializer.update(validated_data, existing_user).await?;
TransactionHelper: RAII-based transaction managementuse reinhardt::rest::serializers::TransactionHelper;
// Wrap operations in transaction
TransactionHelper::with_transaction(|| async {
// All database operations here are atomic
let user = manager.create(user_data).await?;
let profile = manager.create(profile_data).await?;
Ok((user, profile))
}).await?;
// Nested transactions with savepoints
TransactionHelper::savepoint(depth, || async {
// Nested operation with automatic savepoint
manager.update(instance).await
}).await?;
NestedSaveContext: Depth-aware transaction managementuse reinhardt::rest::serializers::NestedSaveContext;
let context = NestedSaveContext::new(depth);
// Automatically uses transaction (depth=0) or savepoint (depth>0)
context.with_scope(|| async {
// Nested serializer save operations
nested_serializer.save(data).await
}).await?;
ManyToManyManager: Junction table operationsuse reinhardt::rest::serializers::ManyToManyManager;
let m2m_manager = ManyToManyManager::<User, Tag>::new(
"user_tags", // Junction table
"user_id", // Source FK
"tag_id" // Target FK
);
// Add multiple relationships
m2m_manager.add_bulk(&user_id, vec![tag1_id, tag2_id, tag3_id]).await?;
// Remove specific relationships
m2m_manager.remove_bulk(&user_id, vec![tag1_id]).await?;
// Replace all relationships atomically
m2m_manager.set(&user_id, vec![tag4_id, tag5_id]).await?;
// Clear all relationships
m2m_manager.clear(&user_id).await?;
PrimaryKeyRelatedFieldORM: Database-backed primary key relationsSlugRelatedFieldORM: Database-backed slug field relationsuse reinhardt::rest::serializers::{PrimaryKeyRelatedFieldORM, SlugRelatedFieldORM};
use reinhardt::db::orm::{Filter, FilterOperator, FilterValue};
// Primary key relation with database validation
let pk_field = PrimaryKeyRelatedFieldORM::<User>::new();
// Validate existence in database
pk_field.validate_exists(&user_id).await?;
// Fetch single instance
let user = pk_field.get_instance(&user_id).await?;
// Batch fetch (prevents N+1 queries)
let users = pk_field.get_instances(vec![id1, id2, id3]).await?;
// Slug field relation with custom filter
let slug_field = SlugRelatedFieldORM::<User>::new("username")
.with_queryset_filter(Filter::new(
"is_active",
FilterOperator::Eq,
FilterValue::Bool(true)
));
// Validate slug exists
slug_field.validate_exists(&slug_value).await?;
// Fetch by slug
let user = slug_field.get_instance(&slug_value).await?;
// Batch fetch by slugs
let users = slug_field.get_instances(vec!["alice", "bob", "charlie"]).await?;
IntrospectionCache: Cache field metadata to avoid repeated introspectionQueryCache: TTL-based query result cachingBatchValidator: Combine multiple database checks into single queriesPerformanceMetrics: Track serialization and validation performanceuse reinhardt::rest::serializers::{IntrospectionCache, QueryCache, BatchValidator, PerformanceMetrics};
use std::time::Duration;
// Cache field introspection results
let cache = IntrospectionCache::new();
if let Some(fields) = cache.get("User") {
// Use cached fields
} else {
let fields = introspect_fields();
cache.set("User".to_string(), fields);
}
// Query result caching with TTL
let query_cache = QueryCache::new(Duration::from_secs(300));
query_cache.set("user:123".to_string(), user_data);
// Batch validation
let mut validator = BatchValidator::new();
validator.add_unique_check("users", "email", "alice@example.com");
validator.add_unique_check("users", "username", "alice");
let failures = validator.execute().await?;
// Performance tracking
let metrics = PerformanceMetrics::new();
metrics.record_serialization(50); // 50ms
let stats = metrics.get_stats();
println!("Average: {}ms", stats.avg_serialization_ms);
Note: ORM integration features (Django-like QuerySet API and SQLAlchemy-like query builder) are available by default. Both patterns can be used interchangeably for database operations.
DateField, DateTimeField: Date and time handling with chrono integrationWritableNestedSerializer: Support updates to nested objectsListSerializer: Serialize collections of objectsYAMLRenderer: Render data as YAMLCSVRenderer: Render data as CSV (for list endpoints)OpenAPIRenderer: Generate OpenAPI/Swagger specificationsField inclusion/exclusion
Read-only/write-only fields
Custom field mappings
Depth control for nested serialization
URLPathVersioning - Version detection from URL path
/v1/users/, /v2.0/api/)with_pattern() method/v1/, /v2.0/, /api/v3/AcceptHeaderVersioning - Version detection from Accept header
Accept: application/json; version=2.0)Accept: application/json; version=1.0QueryParameterVersioning - Version detection from query parameters
?version=1.0, ?v=2.0)with_version_param()?version=1.0, ?v=2.0HostNameVersioning - Version detection from subdomain
v1.api.example.com)with_host_format()with_hostname_pattern()v1.api.example.com, api-v2.example.comNamespaceVersioning - Version detection from URL namespace
/v{version}/)with_namespace_prefix()extract_version_from_router() - Extract version from router pathget_available_versions_from_router() - Get all registered versions/v1/users/, /api/v2/posts/VersioningMiddleware - Automatic version detection and injection
BaseVersioning strategyRequestVersionExt - Type-safe version access from requests
version() - Get version as Option<String>version_or() - Get version with fallback defaultApiVersion - Version data type
as_str() - Get version as string sliceto_string() - Get version as owned Stringnew() - Create new version instanceVersionedHandler - Trait for version-aware handlers
handle_versioned() - Handle request with version contextsupported_versions() - Get list of supported versionssupports_version() - Check version supportVersionedHandlerWrapper - Handler trait adapter
VersionedHandler compatible with standard Handler traitSimpleVersionedHandler - Simple version-to-response mapper
with_version_response() - Add version-specific responsewith_default_response() - Set fallback responseConfigurableVersionedHandler - Advanced handler configuration
with_version_handler() - Add version-specific handlerwith_default_handler() - Set fallback handlerVersionedHandlerBuilder - Builder pattern for handlers
VersionResponseBuilder - Response builder with version metadata
with_data() - Add response datawith_field() - Add individual fieldswith_version_info() - Add version metadataversion() - Get current versionversioned_handler! - Macro for easy handler creation
VersioningConfig - Global configuration
VersioningStrategy - Strategy enumeration
AcceptHeader - Accept header versioningURLPath { pattern } - URL path with custom patternQueryParameter { param_name } - Query parameter with custom nameHostName { patterns } - Hostname with pattern mappingNamespace { pattern } - Namespace with custom patternVersioningManager - Configuration management
config() - Get current configurationversioning() - Get versioning instanceupdate_config() - Update configuration at runtimefrom_env()Environment Configuration - Env var support
REINHARDT_VERSIONING_DEFAULT_VERSION - Default versionREINHARDT_VERSIONING_ALLOWED_VERSIONS - Comma-separated allowed versionsREINHARDT_VERSIONING_STRATEGY - Strategy typeREINHARDT_VERSIONING_STRICT_MODE - Enable/disable strict modeVersionedUrlBuilder - Versioned URL construction
build() - Build URL with default versionbuild_with_version() - Build URL with specific versionbuild_all_versions() - Build URLs for all allowed versionsUrlReverseManager - Multiple builder management
add_builder() - Register named builderwith_default_builder() - Set default builderbuild_url() - Build URL with named builderbuild_default_url() - Build URL with default builderbuild_all_urls() - Build URLs with all buildersApiDocUrlBuilder - API documentation URL builder
/v1.0/openapi.json/v2.0/swagger-ui//v1.0/redoc/ApiDocFormat - Documentation format enum
OpenApi - OpenAPI 3.0 JSONSwagger - Swagger UIReDoc - ReDoc documentationCustom(String) - Custom formatversioned_url! - Macro for URL building
Comprehensive Test Coverage
Test Utilities - test_utils module
create_test_request() - Create mock requests for testingFull Documentation
InvalidAcceptHeader - Malformed Accept headerInvalidURLPath - Invalid URL path formatInvalidNamespace - Invalid namespace formatInvalidHostname - Invalid hostname formatInvalidQueryParameter - Invalid query parameterVersionNotAllowed - Version not in allowed listreinhardt_apps::Errordetermine_version() - Extract version from requestdefault_version() - Get default versionallowed_versions() - Get allowed versionsis_allowed_version() - Check version validityversion_param() - Get version parameter name