api

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultBodyLimit int64 = 32 << 20
View Source
const NonFieldErrors = "__all__"

Variables

View Source
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

func OrderedErrorKeys(errors map[string][]string) []string

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.

func (APIView) AsView

func (v APIView) AsView() View

AsView composes lifecycle hooks around the struct-based view handler.

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

type ActionMetadata struct {
	Name    string
	Methods []string
	Detail  bool
}

ActionMetadata describes one viewset action.

type AuthenticationResult

type AuthenticationResult struct {
	User auth.User
	Auth any
}

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

type AuthenticatorFunc func(context.Context, *Request) (AuthenticationResult, bool, error)

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

func (BrowsableAPIRenderer) Render

func (BrowsableAPIRenderer) Render(value any) ([]byte, string, error)

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

type ExceptionHandler func(context.Context, *Request, error) Response

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

type FieldValidator func(any) error

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

type FilterBackendFunc func(context.Context, *Request, []map[string]any) ([]map[string]any, error)

FilterBackendFunc adapts a function into a filter backend.

func (FilterBackendFunc) Filter

func (f FilterBackendFunc) Filter(ctx context.Context, request *Request, rows []map[string]any) ([]map[string]any, error)

Filter runs the function 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.

func (FilterSet) Apply

func (f FilterSet) Apply(ctx context.Context, request *Request, rows []map[string]any) ([]map[string]any, error)

Apply filters rows using request query parameters and custom backends.

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

func (JSONRenderer) Render

func (JSONRenderer) Render(value any) ([]byte, string, error)

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.

func (*MemoryThrottleStore) Hit

func (s *MemoryThrottleStore) Hit(_ context.Context, key string, now time.Time, window time.Duration) (int, time.Time, error)

Hit increments one throttle key and returns its count and reset time.

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.

func (*MemoryTokenStore) FindToken

func (s *MemoryTokenStore) FindToken(_ context.Context, key string) (Token, bool, error)

FindToken returns a token by key.

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

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.

func (MetadataViewSetStore) Create

func (s MetadataViewSetStore) Create(ctx context.Context, _ *Request, data map[string]any) (map[string]any, error)

func (MetadataViewSetStore) Destroy

func (s MetadataViewSetStore) Destroy(ctx context.Context, _ *Request, lookup string) error

func (MetadataViewSetStore) List

func (s MetadataViewSetStore) List(ctx context.Context, _ *Request) ([]map[string]any, error)

func (MetadataViewSetStore) Retrieve

func (s MetadataViewSetStore) Retrieve(ctx context.Context, _ *Request, lookup string) (map[string]any, error)

func (MetadataViewSetStore) Update

func (s MetadataViewSetStore) Update(ctx context.Context, _ *Request, lookup string, data map[string]any, partial bool) (map[string]any, error)

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) Create

func (s *ModelSerializer) Create(data map[string]any) (map[string]any, error)

Create creates an object from validated data.

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.

func (*ModelSerializer) Update

func (s *ModelSerializer) Update(instance map[string]any, data map[string]any) (map[string]any, error)

Update updates an object from validated data.

func (*ModelSerializer) Validate

func (s *ModelSerializer) Validate(input map[string]any) (map[string]any, map[string][]string, bool)

Validate validates model serializer input.

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.

func (*ModelViewSet) Retrieve

func (v *ModelViewSet) Retrieve(ctx context.Context, request *Request) Response

Retrieve returns one serialized object.

func (*ModelViewSet) Update

func (v *ModelViewSet) Update(ctx context.Context, request *Request) Response

Update replaces one object.

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

type OpenAPIInfo struct {
	Title   string `json:"title"`
	Version string `json:"version"`
}

OpenAPIInfo stores API title and version.

type OpenAPIMediaType

type OpenAPIMediaType struct {
	Schema map[string]any `json:"schema"`
}

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

type OrderedFieldError struct {
	Field    string
	Messages []string
}

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 Parser

type Parser func(*http.Request, int64) (any, error)

Parser parses an HTTP request 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.

func (ParserRegistry) Parse

func (r ParserRegistry) Parse(request *http.Request, limit int64) (any, error)

Parse parses a request using Content-Type and a byte limit.

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 AllowAny

func AllowAny() PermissionClass

AllowAny allows every request.

func CustomObjectPermission

func CustomObjectPermission(check func(context.Context, *Request, any) bool) PermissionClass

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 IsAdminUser

func IsAdminUser() PermissionClass

IsAdminUser allows active staff users.

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

func (PlainTextRenderer) Render

func (PlainTextRenderer) Render(value any) ([]byte, string, error)

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 Rate

type Rate struct {
	Limit  int
	Window time.Duration
}

Rate stores a request limit and fixed window.

func ParseRate

func ParseRate(value string) (Rate, error)

ParseRate parses values such as "100/minute", "10/s", and "1000/day".

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

type Renderer interface {
	MediaType() string
	Render(any) ([]byte, string, error)
}

Renderer serializes an API response body.

func DefaultRenderers

func DefaultRenderers(enableBrowsable bool) []Renderer

DefaultRenderers returns built-in renderers.

func NegotiateRenderer

func NegotiateRenderer(accept string, renderers []Renderer) (Renderer, error)

NegotiateRenderer selects a renderer from an Accept header.

type Request

type Request struct {
	// contains filtered or unexported fields
}

Request wraps a standard HTTP request with API lifecycle metadata.

func NewRequest

func NewRequest(raw *http.Request) *Request

NewRequest wraps a standard HTTP request.

func (*Request) AcceptedRenderer

func (r *Request) AcceptedRenderer() string

AcceptedRenderer returns the selected renderer name.

func (*Request) Auth

func (r *Request) Auth() any

Auth returns authentication metadata.

func (*Request) Method

func (r *Request) Method() string

Method returns the HTTP request method.

func (*Request) ParsedBody

func (r *Request) ParsedBody() any

ParsedBody returns the parsed request body.

func (*Request) PathParam

func (r *Request) PathParam(name string) string

PathParam returns a resolved route path parameter.

func (*Request) QueryParam

func (r *Request) QueryParam(name string) string

QueryParam returns the first query parameter value.

func (*Request) Raw

func (r *Request) Raw() *http.Request

Raw returns the underlying HTTP request.

func (*Request) RemoteIP

func (r *Request) RemoteIP() string

RemoteIP returns the request remote address without a port when possible.

func (*Request) User

func (r *Request) User() auth.User

User returns the authenticated user.

func (*Request) Version

func (r *Request) Version() string

Version returns the resolved API version.

func (*Request) WithAcceptedRenderer

func (r *Request) WithAcceptedRenderer(renderer string) *Request

WithAcceptedRenderer attaches the selected renderer name.

func (*Request) WithAuth

func (r *Request) WithAuth(value any) *Request

WithAuth attaches authentication metadata.

func (*Request) WithParsedBody

func (r *Request) WithParsedBody(body any) *Request

WithParsedBody attaches the parsed request body.

func (*Request) WithPathParam

func (r *Request) WithPathParam(name, value string) *Request

WithPathParam attaches a resolved route path parameter.

func (*Request) WithUser

func (r *Request) WithUser(user auth.User) *Request

WithUser attaches the authenticated user.

func (*Request) WithVersion

func (r *Request) WithVersion(version string) *Request

WithVersion attaches the resolved API version.

type RequestHook

type RequestHook func(context.Context, *Request) error

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

type RequestInitializer func(context.Context, *Request) (*Request, error)

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 Accepted

func Accepted(body any) Response

Accepted creates a 202 JSON response.

func Created

func Created(body any) Response

Created creates a 201 JSON response.

func DefaultExceptionHandler

func DefaultExceptionHandler(_ context.Context, _ *Request, err error) Response

DefaultExceptionHandler returns safe, normalized API errors.

func Error

func Error(status int, err APIError) Response

Error creates a normalized JSON error response.

func File

func File(path, contentType string) Response

File creates a file response.

func JSON

func JSON(status int, body any) Response

JSON creates a JSON response.

func NoContent

func NoContent() Response

NoContent creates a 204 response.

func (Response) HTTP

func (r Response) HTTP() frameworkhttp.Response

HTTP converts an API response into a framework HTTP response.

func (*Response) Header

func (r *Response) Header() http.Header

Header returns mutable response headers.

func (Response) Write

func (r Response) Write(w http.ResponseWriter) error

Write writes the response to a standard response writer.

type ResponseFinalizer

type ResponseFinalizer func(context.Context, *Request, Response) Response

ResponseFinalizer runs after handler or exception responses are produced.

type ResponseSchema

type ResponseSchema struct {
	Description string
	ContentType string
	Schema      map[string]any
}

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

type RouteMetadata struct {
	Name    string
	Pattern string
	Methods []string
	Action  string
	Detail  bool
}

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 NewRouter

func NewRouter(options ...RouterOption) *Router

NewRouter creates an API router.

func (*Router) Handle

func (r *Router) Handle(name, pattern string, view View, methods ...string) error

Handle registers one custom API route.

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) Include

func (r *Router) Include(prefix string, subrouter *Router) error

Include includes another API router under a nested prefix.

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.

func (*Router) Resolve

func (r *Router) Resolve(ctx context.Context, request *Request) (response Response)

Resolve matches one request and runs the route view.

func (*Router) Reverse

func (r *Router) Reverse(name string, args map[string]any) (string, error)

Reverse resolves a route name into a URL path.

func (*Router) Routes

func (r *Router) Routes() []Route

Routes returns a copy of registered route metadata.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w nethttp.ResponseWriter, raw *nethttp.Request)

ServeHTTP serves API routes directly as a standard HTTP handler.

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) Validate

func (s *Serializer) Validate(input map[string]any) (map[string]any, map[string][]string, bool)

Validate parses input into validated data and field errors.

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

type StoredUpload struct {
	Name        string
	Size        int64
	ContentType string
	Location    string
}

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

type ThrottleDecision struct {
	Allowed    bool
	RetryAfter time.Duration
	Key        string
	Scope      string
}

ThrottleDecision is one throttle check result.

type ThrottleError

type ThrottleError struct {
	RetryAfter time.Duration
}

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 Token

type Token struct {
	Key       string
	UserID    int64
	User      auth.User
	CreatedAt time.Time
}

Token is the framework-owned API token model.

func (Token) ModelMeta

func (Token) ModelMeta() models.Metadata

ModelMeta returns metadata for API token persistence.

type TokenStore

type TokenStore interface {
	FindToken(context.Context, string) (Token, bool, error)
}

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

type UploadedFile struct {
	Filename string
	Size     int64
	Content  []byte
}

UploadedFile stores parsed multipart file metadata.

type ValidationErrors

type ValidationErrors map[string][]string

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

type VersioningConfig struct {
	AllowedVersions []string
	DefaultVersion  string
}

VersioningConfig configures allowed and default API versions.

type VersioningStrategy

type VersioningStrategy interface {
	ResolveVersion(*Request) (string, error)
}

VersioningStrategy resolves an API version for one request.

type View

type View func(context.Context, *Request) Response

View handles one API request and returns an API response.

func FunctionView

func FunctionView(handler View) View

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

type ViewSetAction struct {
	Handler View
	Detail  bool
	Methods []string
}

ViewSetAction stores a custom action handler and route metadata.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL