Documentation
¶
Index ¶
- Constants
- Variables
- func CheckObjectPermissions(ctx context.Context, request *Request, object any, classes ...PermissionClass) error
- func ImageSignatureValidator(file UploadedFile) error
- func OrderedErrorKeys(errors map[string][]string) []string
- type APIError
- type APIMetadata
- type APIView
- type AcceptHeaderVersioning
- type ActionMetadata
- type AuthenticationResult
- type Authenticator
- type AuthenticatorFunc
- type BrowsableAPIRenderer
- type CursorPagination
- type ExceptionHandler
- type FieldOptions
- type FieldValidator
- type FilterBackend
- type FilterBackendFunc
- type FilterMetadata
- type FilterSet
- type HostNameVersioning
- type JSONRenderer
- type LimitOffsetPagination
- type MemoryThrottleStore
- type MemoryTokenStore
- type MemoryUploadStorage
- type MetadataOptions
- type MetadataViewSetStore
- func (s MetadataViewSetStore) Create(ctx context.Context, _ *Request, data map[string]any) (map[string]any, error)
- func (s MetadataViewSetStore) Destroy(ctx context.Context, _ *Request, lookup string) error
- func (s MetadataViewSetStore) List(ctx context.Context, _ *Request) ([]map[string]any, error)
- func (s MetadataViewSetStore) Retrieve(ctx context.Context, _ *Request, lookup string) (map[string]any, error)
- func (s MetadataViewSetStore) Update(ctx context.Context, _ *Request, lookup string, data map[string]any, ...) (map[string]any, error)
- type ModelSerializer
- func (s *ModelSerializer) Create(data map[string]any) (map[string]any, error)
- func (s *ModelSerializer) FieldNames() []string
- func (s *ModelSerializer) Render(instance map[string]any) map[string]any
- func (s *ModelSerializer) Update(instance map[string]any, data map[string]any) (map[string]any, error)
- func (s *ModelSerializer) Validate(input map[string]any) (map[string]any, map[string][]string, bool)
- type ModelSerializerConfig
- type ModelViewSet
- func (v *ModelViewSet) AsView(action string) View
- func (v *ModelViewSet) Create(ctx context.Context, request *Request) Response
- func (v *ModelViewSet) Destroy(ctx context.Context, request *Request) Response
- func (v *ModelViewSet) List(ctx context.Context, request *Request) Response
- func (v *ModelViewSet) PartialUpdate(ctx context.Context, request *Request) Response
- func (v *ModelViewSet) RegisterAction(name string, action ViewSetAction)
- func (v *ModelViewSet) Retrieve(ctx context.Context, request *Request) Response
- func (v *ModelViewSet) Update(ctx context.Context, request *Request) Response
- type ModelViewSetStore
- type MultipartBody
- type NamespaceVersioning
- type ObjectValidator
- type OpenAPIComponents
- type OpenAPIExternalDocs
- type OpenAPIInfo
- type OpenAPIMediaType
- type OpenAPIOperation
- type OpenAPIOptions
- type OpenAPIParameter
- type OpenAPIPathItem
- type OpenAPIRequestBody
- type OpenAPISpec
- type OperationMetadata
- type OrderedFieldError
- type PageNumberPagination
- type PaginatedResult
- type Parser
- type ParserRegistry
- type PermissionClass
- func AllowAny() PermissionClass
- func CustomObjectPermission(check func(context.Context, *Request, any) bool) PermissionClass
- func CustomPermission(check func(context.Context, *Request) bool) PermissionClass
- func IsAdminUser() PermissionClass
- func IsAuthenticated() PermissionClass
- func IsAuthenticatedOrReadOnly() PermissionClass
- func ModelPermissions(appLabel, model string) PermissionClass
- type PlainTextRenderer
- type QueryParameterVersioning
- type Rate
- type RateThrottle
- type Renderer
- type Request
- func (r *Request) AcceptedRenderer() string
- func (r *Request) Auth() any
- func (r *Request) Method() string
- func (r *Request) ParsedBody() any
- func (r *Request) PathParam(name string) string
- func (r *Request) QueryParam(name string) string
- func (r *Request) Raw() *http.Request
- func (r *Request) RemoteIP() string
- func (r *Request) User() auth.User
- func (r *Request) Version() string
- func (r *Request) WithAcceptedRenderer(renderer string) *Request
- func (r *Request) WithAuth(value any) *Request
- func (r *Request) WithParsedBody(body any) *Request
- func (r *Request) WithPathParam(name, value string) *Request
- func (r *Request) WithUser(user auth.User) *Request
- func (r *Request) WithVersion(version string) *Request
- type RequestHook
- type RequestInitializer
- type Response
- func Accepted(body any) Response
- func Created(body any) Response
- func DefaultExceptionHandler(_ context.Context, _ *Request, err error) Response
- func Error(status int, err APIError) Response
- func File(path, contentType string) Response
- func JSON(status int, body any) Response
- func NoContent() Response
- type ResponseFinalizer
- type ResponseSchema
- type Route
- type RouteMetadata
- type Router
- func (r *Router) Handle(name, pattern string, view View, methods ...string) error
- func (r *Router) HandleHTTP(name, pattern string, handler nethttp.Handler, metadata OperationMetadata, ...) error
- func (r *Router) Include(prefix string, subrouter *Router) error
- func (r *Router) MountHTTP(router *frameworkhttp.Router) error
- func (r *Router) Register(prefix, basename string, viewset *ModelViewSet) error
- func (r *Router) Resolve(ctx context.Context, request *Request) (response Response)
- func (r *Router) Reverse(name string, args map[string]any) (string, error)
- func (r *Router) Routes() []Route
- func (r *Router) ServeHTTP(w nethttp.ResponseWriter, raw *nethttp.Request)
- type RouterOption
- type Serializer
- func (s *Serializer) Render(obj map[string]any) map[string]any
- func (s *Serializer) Validate(input map[string]any) (map[string]any, map[string][]string, bool)
- func (s *Serializer) ValidatePartial(input map[string]any) (map[string]any, map[string][]string, bool)
- func (s *Serializer) WithObjectValidators(validators ...ObjectValidator) *Serializer
- type SerializerField
- func BooleanField(name string, options FieldOptions) SerializerField
- func ChoiceField(name string, options FieldOptions, choices []string) SerializerField
- func DateField(name string, options FieldOptions) SerializerField
- func DateTimeField(name string, options FieldOptions) SerializerField
- func DecimalField(name string, options FieldOptions) SerializerField
- func DictField(name string, options FieldOptions) SerializerField
- func DurationField(name string, options FieldOptions) SerializerField
- func EmailField(name string, options FieldOptions) SerializerField
- func FileField(name string, options FieldOptions) SerializerField
- func FloatField(name string, options FieldOptions) SerializerField
- func HyperlinkedRelatedField(name string, options FieldOptions) SerializerField
- func ImageField(name string, options FieldOptions) SerializerField
- func IntegerField(name string, options FieldOptions) SerializerField
- func JSONField(name string, options FieldOptions) SerializerField
- func ListField(name string, options FieldOptions, child SerializerField) SerializerField
- func MethodField(name string, method func(map[string]any) any) SerializerField
- func MultipleChoiceField(name string, options FieldOptions, choices []string) SerializerField
- func NestedObjectField(name string, options FieldOptions, serializer *Serializer) SerializerField
- func PrimaryKeyRelatedField(name string, options FieldOptions) SerializerField
- func SlugField(name string, options FieldOptions) SerializerField
- func SlugRelatedField(name string, options FieldOptions) SerializerField
- func StringField(name string, options FieldOptions) SerializerField
- func TimeField(name string, options FieldOptions) SerializerField
- func URLField(name string, options FieldOptions) SerializerField
- func UUIDField(name string, options FieldOptions) SerializerField
- type SerializerFieldMetadata
- type SerializerMetadata
- type StoredUpload
- type Throttle
- type ThrottleDecision
- type ThrottleError
- type ThrottleStore
- type Token
- type TokenStore
- type URLPathVersioning
- type UploadConfig
- type UploadHandler
- func (h UploadHandler) HandleMultipart(ctx context.Context, request *Request) ([]StoredUpload, error)
- func (h UploadHandler) HandleStream(ctx context.Context, request *Request, filename string) (StoredUpload, error)
- func (h UploadHandler) SaveUploadedFile(ctx context.Context, file UploadedFile) (StoredUpload, error)
- type UploadStorage
- type UploadedFile
- type ValidationErrors
- type VersioningConfig
- type VersioningStrategy
- type View
- type ViewSetAction
Constants ¶
const DefaultBodyLimit int64 = 32 << 20
const NonFieldErrors = "__all__"
Variables ¶
var ( ErrUnsupportedMediaType = errors.New("unsupported media type") ErrParse = errors.New("parse error") ErrBodyTooLarge = errors.New("body too large") ErrNotAcceptable = errors.New("not acceptable") ErrValidation = errors.New("validation error") ErrInvalidSerializerConfig = errors.New("invalid serializer config") ErrAuthenticationFailed = errors.New("authentication failed") ErrPermissionDenied = errors.New("permission denied") ErrThrottled = errors.New("request throttled") ErrNotFound = errors.New("not found") ErrMethodNotAllowed = errors.New("method not allowed") ErrInternal = errors.New("internal error") ErrRouteConflict = errors.New("route conflict") ErrReverse = errors.New("reverse error") ErrPagination = errors.New("pagination error") ErrFilter = errors.New("filter error") ErrUpload = errors.New("upload error") ErrVersion = errors.New("version error") )
Functions ¶
func CheckObjectPermissions ¶
func CheckObjectPermissions(ctx context.Context, request *Request, object any, classes ...PermissionClass) error
CheckObjectPermissions evaluates object-level permissions.
func ImageSignatureValidator ¶
func ImageSignatureValidator(file UploadedFile) error
ImageSignatureValidator accepts PNG, JPEG, and GIF upload signatures.
func OrderedErrorKeys ¶
OrderedErrorKeys returns field names in deterministic API response order.
Types ¶
type APIError ¶
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
Fields map[string][]string `json:"fields,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
APIError is the normalized API error body.
type APIMetadata ¶
type APIMetadata struct {
Version string
BrowsableAPI bool
Routes []RouteMetadata
Actions []ActionMetadata
Serializer SerializerMetadata
Forms map[string][]SerializerFieldMetadata
Filters FilterMetadata
Pagination string
Authentication []string
Permissions []string
Throttles []string
}
APIMetadata describes routes and policies for browsable API, OPTIONS, and schema generation.
func BuildMetadata ¶
func BuildMetadata(request *Request, router *Router, options MetadataOptions) APIMetadata
BuildMetadata returns API endpoint metadata from router and component options.
type APIView ¶
type APIView struct {
Handler View
ParserRegistry ParserRegistry
ParseBody bool
BodyLimit int64
InitializeRequest RequestInitializer
CheckAuthentication RequestHook
CheckPermissions RequestHook
CheckThrottles RequestHook
HandleException ExceptionHandler
FinalizeResponse ResponseFinalizer
}
APIView is the struct-based API view with Django REST Framework-style hooks.
type AcceptHeaderVersioning ¶
type AcceptHeaderVersioning struct {
Config VersioningConfig
}
AcceptHeaderVersioning resolves versions from an Accept header version parameter.
func (AcceptHeaderVersioning) ResolveVersion ¶
func (v AcceptHeaderVersioning) ResolveVersion(request *Request) (string, error)
ResolveVersion resolves Accept header versions.
type ActionMetadata ¶
ActionMetadata describes one viewset action.
type AuthenticationResult ¶
AuthenticationResult is the result of one successful authenticator.
type Authenticator ¶
type Authenticator interface {
Authenticate(context.Context, *Request) (AuthenticationResult, bool, error)
}
Authenticator authenticates one API request.
func SessionAuthentication ¶
func SessionAuthentication() Authenticator
SessionAuthentication authenticates users already attached by the auth middleware.
func TokenAuthentication ¶
func TokenAuthentication(store TokenStore) Authenticator
TokenAuthentication authenticates Authorization: Token <key> requests.
type AuthenticatorFunc ¶
AuthenticatorFunc adapts a function into an authenticator.
func (AuthenticatorFunc) Authenticate ¶
func (f AuthenticatorFunc) Authenticate(ctx context.Context, request *Request) (AuthenticationResult, bool, error)
Authenticate runs the function authenticator.
type BrowsableAPIRenderer ¶
type BrowsableAPIRenderer struct{}
BrowsableAPIRenderer renders minimal HTML metadata.
func (BrowsableAPIRenderer) MediaType ¶
func (BrowsableAPIRenderer) MediaType() string
type CursorPagination ¶
type CursorPagination struct {
PageSize int
MaxPageSize int
Ordering string
CursorQueryParam string
PageSizeQueryParam string
}
CursorPagination paginates ordered items after an encoded cursor value.
func (CursorPagination) Paginate ¶
func (p CursorPagination) Paginate(request *Request, items []any) (PaginatedResult, error)
Paginate returns one cursor page of items.
type ExceptionHandler ¶
ExceptionHandler converts lifecycle errors into API responses.
type FieldOptions ¶
type FieldOptions struct {
Required bool
AllowNull bool
AllowBlank bool
Default any
Source string
Label string
HelpText string
ReadOnly bool
WriteOnly bool
Validators []FieldValidator
ErrorMessages map[string]string
}
FieldOptions configures serializer field behavior.
type FieldValidator ¶
func UniqueValidator ¶
func UniqueValidator(check func(any) (bool, error)) FieldValidator
UniqueValidator validates a single field value with an application lookup.
type FilterBackend ¶
type FilterBackend interface {
Filter(context.Context, *Request, []map[string]any) ([]map[string]any, error)
}
FilterBackend filters API result rows.
type FilterBackendFunc ¶
FilterBackendFunc adapts a function into a filter backend.
type FilterMetadata ¶
type FilterMetadata struct {
Exact []string
Lookups map[string][]string
Search []string
Ordering []string
}
FilterMetadata describes filter controls.
type FilterSet ¶
type FilterSet struct {
ExactFields []string
LookupFields map[string][]string
SearchFields []string
OrderingFields []string
Distinct bool
DistinctFields []string
Backends []FilterBackend
SearchParam string
OrderingParam string
}
FilterSet configures safe API filtering, search, ordering, and distinct handling.
type HostNameVersioning ¶
type HostNameVersioning struct {
Config VersioningConfig
}
HostNameVersioning resolves versions from the first hostname label.
func (HostNameVersioning) ResolveVersion ¶
func (v HostNameVersioning) ResolveVersion(request *Request) (string, error)
ResolveVersion resolves hostname versions.
type JSONRenderer ¶
type JSONRenderer struct{}
JSONRenderer renders JSON.
func (JSONRenderer) MediaType ¶
func (JSONRenderer) MediaType() string
type LimitOffsetPagination ¶
type LimitOffsetPagination struct {
DefaultLimit int
MaxLimit int
LimitParam string
OffsetParam string
}
LimitOffsetPagination paginates with limit and offset query parameters.
func (LimitOffsetPagination) Paginate ¶
func (p LimitOffsetPagination) Paginate(request *Request, items []any) (PaginatedResult, error)
Paginate returns one limit/offset page of items.
type MemoryThrottleStore ¶
type MemoryThrottleStore struct {
// contains filtered or unexported fields
}
MemoryThrottleStore stores throttle counters in memory.
func NewMemoryThrottleStore ¶
func NewMemoryThrottleStore() *MemoryThrottleStore
NewMemoryThrottleStore creates an in-memory throttle store.
type MemoryTokenStore ¶
type MemoryTokenStore struct {
// contains filtered or unexported fields
}
MemoryTokenStore is an in-memory token store for tests, examples, and bootstrapping.
func NewMemoryTokenStore ¶
func NewMemoryTokenStore(tokens ...Token) *MemoryTokenStore
NewMemoryTokenStore creates an in-memory token store.
func (*MemoryTokenStore) Add ¶
func (s *MemoryTokenStore) Add(token Token)
Add inserts or replaces a token.
type MemoryUploadStorage ¶
type MemoryUploadStorage struct {
Files []StoredUpload
Contents map[string][]byte
}
MemoryUploadStorage stores uploads in memory for tests, examples, and bootstrapping.
func NewMemoryUploadStorage ¶
func NewMemoryUploadStorage() *MemoryUploadStorage
NewMemoryUploadStorage creates an in-memory upload storage.
func (*MemoryUploadStorage) SaveUpload ¶
func (s *MemoryUploadStorage) SaveUpload(_ context.Context, file UploadedFile) (StoredUpload, error)
SaveUpload stores one upload.
type MetadataOptions ¶
type MetadataOptions struct {
Serializer *Serializer
FilterSet FilterSet
Pagination any
Authentication []string
Permissions []string
Throttles []string
}
MetadataOptions configures endpoint metadata generation.
type MetadataViewSetStore ¶
type MetadataViewSetStore struct {
Store *orm.MetadataStore
Model models.Metadata
}
MetadataViewSetStore adapts an ORM metadata store to ModelViewSetStore.
func NewMetadataViewSetStore ¶
func NewMetadataViewSetStore(store *orm.MetadataStore, meta models.Metadata) MetadataViewSetStore
NewMetadataViewSetStore creates a model-backed API viewset store.
type ModelSerializer ¶
type ModelSerializer struct {
// contains filtered or unexported fields
}
ModelSerializer maps model metadata to serializer fields.
func NewModelSerializer ¶
func NewModelSerializer(config ModelSerializerConfig) (*ModelSerializer, error)
NewModelSerializer builds a serializer from model metadata.
func (*ModelSerializer) FieldNames ¶
func (s *ModelSerializer) FieldNames() []string
FieldNames returns serializer field order.
func (*ModelSerializer) Render ¶
func (s *ModelSerializer) Render(instance map[string]any) map[string]any
Render renders a model instance map.
type ModelSerializerConfig ¶
type ModelSerializerConfig struct {
Model models.Metadata
Fields []string
Exclude []string
ReadOnlyFields []string
ExtraKwargs map[string]FieldOptions
Depth int
NestedSerializers map[string]*Serializer
CreateFunc func(map[string]any) (map[string]any, error)
UpdateFunc func(map[string]any, map[string]any) (map[string]any, error)
}
ModelSerializerConfig configures metadata-driven serializers.
type ModelViewSet ¶
type ModelViewSet struct {
Store ModelViewSetStore
Serializer *Serializer
LookupParam string
View APIView
Actions map[string]ViewSetAction
}
ModelViewSet provides list, retrieve, create, update, partial update, destroy, and custom actions.
func (*ModelViewSet) AsView ¶
func (v *ModelViewSet) AsView(action string) View
AsView returns an API view for a named viewset action.
func (*ModelViewSet) Create ¶
func (v *ModelViewSet) Create(ctx context.Context, request *Request) Response
Create validates and creates one object.
func (*ModelViewSet) Destroy ¶
func (v *ModelViewSet) Destroy(ctx context.Context, request *Request) Response
Destroy deletes one object.
func (*ModelViewSet) List ¶
func (v *ModelViewSet) List(ctx context.Context, request *Request) Response
List returns serialized objects.
func (*ModelViewSet) PartialUpdate ¶
func (v *ModelViewSet) PartialUpdate(ctx context.Context, request *Request) Response
PartialUpdate updates one object with partial input.
func (*ModelViewSet) RegisterAction ¶
func (v *ModelViewSet) RegisterAction(name string, action ViewSetAction)
RegisterAction registers a custom action on the viewset.
type ModelViewSetStore ¶
type ModelViewSetStore interface {
List(context.Context, *Request) ([]map[string]any, error)
Retrieve(context.Context, *Request, string) (map[string]any, error)
Create(context.Context, *Request, map[string]any) (map[string]any, error)
Update(context.Context, *Request, string, map[string]any, bool) (map[string]any, error)
Destroy(context.Context, *Request, string) error
}
ModelViewSetStore is the persistence boundary used by model viewsets.
type MultipartBody ¶
type MultipartBody struct {
Values map[string][]string
Files map[string][]UploadedFile
}
MultipartBody stores multipart values and files.
type NamespaceVersioning ¶
type NamespaceVersioning struct {
Config VersioningConfig
Param string
}
NamespaceVersioning resolves versions from a path parameter.
func (NamespaceVersioning) ResolveVersion ¶
func (v NamespaceVersioning) ResolveVersion(request *Request) (string, error)
ResolveVersion resolves namespace path parameter versions.
type ObjectValidator ¶
type ObjectValidator func(map[string]any) ValidationErrors
ObjectValidator validates a complete serializer value map.
func ModelValidationValidator ¶
func ModelValidationValidator(ctx context.Context, validators ...modelvalidation.Validator) ObjectValidator
ModelValidationValidator reuses model validation validators inside API serializers.
func UniqueTogetherValidator ¶
func UniqueTogetherValidator(fields []string, check func(map[string]any) (bool, error)) ObjectValidator
UniqueTogetherValidator validates that a field set is unique together.
type OpenAPIComponents ¶
type OpenAPIComponents struct {
Schemas map[string]any `json:"schemas"`
Responses map[string]any `json:"responses"`
SecuritySchemes map[string]map[string]any `json:"securitySchemes,omitempty"`
}
OpenAPIComponents stores reusable schemas, responses, and security schemes.
type OpenAPIExternalDocs ¶
type OpenAPIExternalDocs struct {
URL string `json:"url,omitempty"`
}
OpenAPIExternalDocs stores optional documentation links.
type OpenAPIInfo ¶
OpenAPIInfo stores API title and version.
type OpenAPIMediaType ¶
OpenAPIMediaType wraps a schema.
type OpenAPIOperation ¶
type OpenAPIOperation struct {
OperationID string `json:"operationId"`
Parameters []OpenAPIParameter `json:"parameters,omitempty"`
RequestBody *OpenAPIRequestBody `json:"requestBody,omitempty"`
Responses map[string]any `json:"responses"`
Security []map[string][]string `json:"security,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Tags []string `json:"tags,omitempty"`
}
OpenAPIOperation describes one operation.
type OpenAPIOptions ¶
type OpenAPIOptions struct {
Title string
Version string
Router *Router
Serializer *Serializer
Pagination any
Authentication []string
AdminDocsURL string
}
OpenAPIOptions configures OpenAPI generation.
type OpenAPIParameter ¶
type OpenAPIParameter struct {
In string `json:"in"`
Name string `json:"name"`
Required bool `json:"required"`
Schema map[string]any `json:"schema"`
}
OpenAPIParameter describes an operation parameter.
type OpenAPIPathItem ¶
type OpenAPIPathItem map[string]OpenAPIOperation
OpenAPIPathItem maps HTTP methods to operations.
type OpenAPIRequestBody ¶
type OpenAPIRequestBody struct {
Required bool `json:"required"`
Content map[string]OpenAPIMediaType `json:"content"`
}
OpenAPIRequestBody describes operation request content.
type OpenAPISpec ¶
type OpenAPISpec struct {
OpenAPI string `json:"openapi"`
Info OpenAPIInfo `json:"info"`
ExternalDocs OpenAPIExternalDocs `json:"externalDocs,omitempty"`
Paths map[string]OpenAPIPathItem `json:"paths"`
Components OpenAPIComponents `json:"components"`
Security []map[string][]string `json:"security,omitempty"`
}
OpenAPISpec is an OpenAPI 3.1 document.
func GenerateOpenAPI ¶
func GenerateOpenAPI(options OpenAPIOptions) OpenAPISpec
GenerateOpenAPI builds an OpenAPI 3.1 document.
type OperationMetadata ¶
type OperationMetadata struct {
Summary string
Description string
Tags []string
Responses map[int]ResponseSchema
}
OperationMetadata documents a custom or raw API route for OpenAPI generation.
type OrderedFieldError ¶
OrderedFieldError is a deterministic field error entry for API responses.
func OrderedFieldErrors ¶
func OrderedFieldErrors(errors map[string][]string) []OrderedFieldError
OrderedFieldErrors returns deterministic field error entries for API responses.
type PageNumberPagination ¶
type PageNumberPagination struct {
PageSize int
MaxPageSize int
PageQueryParam string
PageSizeQueryParam string
}
PageNumberPagination paginates with page and page_size query parameters.
func (PageNumberPagination) Paginate ¶
func (p PageNumberPagination) Paginate(request *Request, items []any) (PaginatedResult, error)
Paginate returns one page of items.
type PaginatedResult ¶
type PaginatedResult struct {
Count int `json:"count"`
Next string `json:"next,omitempty"`
Previous string `json:"previous,omitempty"`
Results []any `json:"results"`
}
PaginatedResult is the normalized pagination response body.
type ParserRegistry ¶
type ParserRegistry struct {
// contains filtered or unexported fields
}
ParserRegistry maps media types to parsers.
func DefaultParserRegistry ¶
func DefaultParserRegistry() ParserRegistry
DefaultParserRegistry returns built-in parsers.
type PermissionClass ¶
type PermissionClass interface {
HasPermission(context.Context, *Request) bool
HasObjectPermission(context.Context, *Request, any) bool
}
PermissionClass evaluates request and object-level API access.
func CustomObjectPermission ¶
CustomObjectPermission creates an object-level permission class.
func CustomPermission ¶
func CustomPermission(check func(context.Context, *Request) bool) PermissionClass
CustomPermission creates a request-level permission class.
func IsAuthenticated ¶
func IsAuthenticated() PermissionClass
IsAuthenticated allows active authenticated users.
func IsAuthenticatedOrReadOnly ¶
func IsAuthenticatedOrReadOnly() PermissionClass
IsAuthenticatedOrReadOnly allows safe methods or authenticated writes.
func ModelPermissions ¶
func ModelPermissions(appLabel, model string) PermissionClass
ModelPermissions maps HTTP methods to Django-style model permissions.
type PlainTextRenderer ¶
type PlainTextRenderer struct{}
PlainTextRenderer renders errors as text.
func (PlainTextRenderer) MediaType ¶
func (PlainTextRenderer) MediaType() string
type QueryParameterVersioning ¶
type QueryParameterVersioning struct {
Config VersioningConfig
Param string
}
QueryParameterVersioning resolves versions from a query parameter.
func (QueryParameterVersioning) ResolveVersion ¶
func (v QueryParameterVersioning) ResolveVersion(request *Request) (string, error)
ResolveVersion resolves query parameter versions.
type RateThrottle ¶
type RateThrottle struct {
Scope string
Rate Rate
Store ThrottleStore
Identity func(*Request) string
Now func() time.Time
}
RateThrottle is a fixed-window throttle.
func AnonymousRateThrottle ¶
func AnonymousRateThrottle(rate Rate, store ThrottleStore) *RateThrottle
AnonymousRateThrottle throttles anonymous requests by remote IP.
func ScopedRateThrottle ¶
func ScopedRateThrottle(scope string, rate Rate, store ThrottleStore) *RateThrottle
ScopedRateThrottle throttles requests by scope and request identity.
func UserRateThrottle ¶
func UserRateThrottle(rate Rate, store ThrottleStore) *RateThrottle
UserRateThrottle throttles authenticated users by user ID and anonymous users by IP.
func (*RateThrottle) Allow ¶
func (t *RateThrottle) Allow(ctx context.Context, request *Request) (ThrottleDecision, error)
Allow checks one request against the throttle store.
type Renderer ¶
Renderer serializes an API response body.
func DefaultRenderers ¶
DefaultRenderers returns built-in renderers.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request wraps a standard HTTP request with API lifecycle metadata.
func NewRequest ¶
NewRequest wraps a standard HTTP request.
func (*Request) AcceptedRenderer ¶
AcceptedRenderer returns the selected renderer name.
func (*Request) ParsedBody ¶
ParsedBody returns the parsed request body.
func (*Request) QueryParam ¶
QueryParam returns the first query parameter value.
func (*Request) RemoteIP ¶
RemoteIP returns the request remote address without a port when possible.
func (*Request) WithAcceptedRenderer ¶
WithAcceptedRenderer attaches the selected renderer name.
func (*Request) WithParsedBody ¶
WithParsedBody attaches the parsed request body.
func (*Request) WithPathParam ¶
WithPathParam attaches a resolved route path parameter.
func (*Request) WithVersion ¶
WithVersion attaches the resolved API version.
type RequestHook ¶
RequestHook validates one request lifecycle stage.
func AuthenticateRequest ¶
func AuthenticateRequest(authenticators ...Authenticator) RequestHook
AuthenticateRequest creates an APIView authentication lifecycle hook.
func CheckPermissions ¶
func CheckPermissions(classes ...PermissionClass) RequestHook
CheckPermissions creates an APIView permission lifecycle hook.
func CheckThrottles ¶
func CheckThrottles(throttles ...Throttle) RequestHook
CheckThrottles creates an APIView throttle lifecycle hook.
func VersionRequest ¶
func VersionRequest(strategy VersioningStrategy) RequestHook
VersionRequest creates an APIView lifecycle hook that attaches the resolved version.
type RequestInitializer ¶
RequestInitializer prepares a request before authentication and parsing.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response is an API response writer.
func DefaultExceptionHandler ¶
DefaultExceptionHandler returns safe, normalized API errors.
func (Response) HTTP ¶
func (r Response) HTTP() frameworkhttp.Response
HTTP converts an API response into a framework HTTP response.
type ResponseFinalizer ¶
ResponseFinalizer runs after handler or exception responses are produced.
type ResponseSchema ¶
ResponseSchema documents one OpenAPI response for a custom or raw API route.
type Route ¶
type Route struct {
Name string
Pattern string
Methods []string
Action string
Detail bool
View View
HTTPHandler nethttp.Handler
Metadata OperationMetadata
// contains filtered or unexported fields
}
Route stores generated API route metadata.
type RouteMetadata ¶
RouteMetadata describes one API route.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router stores generated API routes and resolves requests to API views.
func (*Router) HandleHTTP ¶
func (r *Router) HandleHTTP(name, pattern string, handler nethttp.Handler, metadata OperationMetadata, methods ...string) error
HandleHTTP registers one raw standard-library API route with documentation metadata.
func (*Router) MountHTTP ¶
func (r *Router) MountHTTP(router *frameworkhttp.Router) error
MountHTTP registers API routes on a framework HTTP router.
func (*Router) Register ¶
func (r *Router) Register(prefix, basename string, viewset *ModelViewSet) error
Register registers all standard routes and custom actions for a viewset.
type RouterOption ¶
type RouterOption func(*Router)
RouterOption configures an API router.
func WithAPIPrefix ¶
func WithAPIPrefix(prefix string) RouterOption
WithAPIPrefix configures a path prefix for routes registered on the router.
func WithExceptionHandler ¶
func WithExceptionHandler(handler ExceptionHandler) RouterOption
WithExceptionHandler configures router-level exception handling for route misses, method errors, write failures, and uncaught API view panics.
func WithTrailingSlash ¶
func WithTrailingSlash(enabled bool) RouterOption
WithTrailingSlash enables or disables generated trailing slashes.
type Serializer ¶
type Serializer struct {
// contains filtered or unexported fields
}
Serializer validates input and renders output using ordered fields.
func NewSerializer ¶
func NewSerializer(fields ...SerializerField) *Serializer
NewSerializer creates a serializer from fields.
func (*Serializer) Render ¶
func (s *Serializer) Render(obj map[string]any) map[string]any
Render serializes an object map.
func (*Serializer) ValidatePartial ¶
func (s *Serializer) ValidatePartial(input map[string]any) (map[string]any, map[string][]string, bool)
ValidatePartial parses input while allowing required fields to be omitted.
func (*Serializer) WithObjectValidators ¶
func (s *Serializer) WithObjectValidators(validators ...ObjectValidator) *Serializer
WithObjectValidators appends cross-field validators to the serializer.
type SerializerField ¶
type SerializerField struct {
Name string
Kind string
Options FieldOptions
Choices []string
Child *SerializerField
Nested *Serializer
MethodFunc func(map[string]any) any
}
SerializerField parses and renders one serializer value.
func BooleanField ¶
func BooleanField(name string, options FieldOptions) SerializerField
func ChoiceField ¶
func ChoiceField(name string, options FieldOptions, choices []string) SerializerField
func DateField ¶
func DateField(name string, options FieldOptions) SerializerField
func DateTimeField ¶
func DateTimeField(name string, options FieldOptions) SerializerField
func DecimalField ¶
func DecimalField(name string, options FieldOptions) SerializerField
func DictField ¶
func DictField(name string, options FieldOptions) SerializerField
func DurationField ¶
func DurationField(name string, options FieldOptions) SerializerField
func EmailField ¶
func EmailField(name string, options FieldOptions) SerializerField
func FileField ¶
func FileField(name string, options FieldOptions) SerializerField
func FloatField ¶
func FloatField(name string, options FieldOptions) SerializerField
func HyperlinkedRelatedField ¶
func HyperlinkedRelatedField(name string, options FieldOptions) SerializerField
func ImageField ¶
func ImageField(name string, options FieldOptions) SerializerField
func IntegerField ¶
func IntegerField(name string, options FieldOptions) SerializerField
func JSONField ¶
func JSONField(name string, options FieldOptions) SerializerField
func ListField ¶
func ListField(name string, options FieldOptions, child SerializerField) SerializerField
func MethodField ¶
func MethodField(name string, method func(map[string]any) any) SerializerField
func MultipleChoiceField ¶
func MultipleChoiceField(name string, options FieldOptions, choices []string) SerializerField
func NestedObjectField ¶
func NestedObjectField(name string, options FieldOptions, serializer *Serializer) SerializerField
func PrimaryKeyRelatedField ¶
func PrimaryKeyRelatedField(name string, options FieldOptions) SerializerField
func SlugField ¶
func SlugField(name string, options FieldOptions) SerializerField
func SlugRelatedField ¶
func SlugRelatedField(name string, options FieldOptions) SerializerField
func StringField ¶
func StringField(name string, options FieldOptions) SerializerField
func TimeField ¶
func TimeField(name string, options FieldOptions) SerializerField
func URLField ¶
func URLField(name string, options FieldOptions) SerializerField
func UUIDField ¶
func UUIDField(name string, options FieldOptions) SerializerField
type SerializerFieldMetadata ¶
type SerializerFieldMetadata struct {
Name string
Kind string
Source string
Required bool
ReadOnly bool
WriteOnly bool
Label string
HelpText string
Choices []string
}
SerializerFieldMetadata describes one serializer field.
type SerializerMetadata ¶
type SerializerMetadata struct {
Fields []SerializerFieldMetadata
}
SerializerMetadata describes serializer fields.
func SerializerMetadataFor ¶
func SerializerMetadataFor(serializer *Serializer) SerializerMetadata
SerializerMetadataFor returns metadata for serializer fields.
type StoredUpload ¶
StoredUpload is the storage result for one uploaded file.
type Throttle ¶
type Throttle interface {
Allow(context.Context, *Request) (ThrottleDecision, error)
}
Throttle checks whether a request may continue.
type ThrottleDecision ¶
ThrottleDecision is one throttle check result.
type ThrottleError ¶
ThrottleError carries retry timing for throttled requests.
func (*ThrottleError) Error ¶
func (e *ThrottleError) Error() string
func (*ThrottleError) Unwrap ¶
func (e *ThrottleError) Unwrap() error
type ThrottleStore ¶
type ThrottleStore interface {
Hit(context.Context, string, time.Time, time.Duration) (int, time.Time, error)
}
ThrottleStore stores request counters.
type TokenStore ¶
TokenStore looks up API tokens.
type URLPathVersioning ¶
type URLPathVersioning struct {
Config VersioningConfig
}
URLPathVersioning resolves versions from the first URL path segment.
func (URLPathVersioning) ResolveVersion ¶
func (v URLPathVersioning) ResolveVersion(request *Request) (string, error)
ResolveVersion resolves URL path versions.
type UploadConfig ¶
type UploadConfig struct {
FieldName string
MaxSize int64
AllowedExtensions []string
ImageValidator func(UploadedFile) error
Storage UploadStorage
}
UploadConfig configures upload validation and storage.
type UploadHandler ¶
type UploadHandler struct {
Config UploadConfig
}
UploadHandler validates and stores multipart or streamed uploads.
func (UploadHandler) HandleMultipart ¶
func (h UploadHandler) HandleMultipart(ctx context.Context, request *Request) ([]StoredUpload, error)
HandleMultipart parses, validates, and stores multipart uploads.
func (UploadHandler) HandleStream ¶
func (h UploadHandler) HandleStream(ctx context.Context, request *Request, filename string) (StoredUpload, error)
HandleStream validates and stores a raw request body as one file.
func (UploadHandler) SaveUploadedFile ¶
func (h UploadHandler) SaveUploadedFile(ctx context.Context, file UploadedFile) (StoredUpload, error)
SaveUploadedFile validates and stores one parsed upload.
type UploadStorage ¶
type UploadStorage interface {
SaveUpload(context.Context, UploadedFile) (StoredUpload, error)
}
UploadStorage stores validated uploads.
type UploadedFile ¶
UploadedFile stores parsed multipart file metadata.
type ValidationErrors ¶
ValidationErrors stores serializer validation messages by field name.
func FromModelValidationError ¶
func FromModelValidationError(err error) ValidationErrors
FromModelValidationError converts model validation errors into API field errors.
func (ValidationErrors) Add ¶
func (e ValidationErrors) Add(field, message string)
Add appends a message to a field.
type VersioningConfig ¶
VersioningConfig configures allowed and default API versions.
type VersioningStrategy ¶
VersioningStrategy resolves an API version for one request.
type View ¶
View handles one API request and returns an API response.
func FunctionView ¶
FunctionView adapts a function API view through the default lifecycle.
func OpenAPIJSONView ¶
func OpenAPIJSONView(spec OpenAPISpec) View
OpenAPIJSONView returns an API view that serves an OpenAPI document.
type ViewSetAction ¶
ViewSetAction stores a custom action handler and route metadata.