dartapi_core library

Classes

ApiRoute<ApiInput, ApiOutput>
Represents a single HTTP route in your DartAPI application.
AppConfig
Convenience EnvConfig subclass with the fields common to most DartAPI projects (server port, debug mode, log level, database, JWT, CORS).
BackgroundTaskQueue
A queue of async callbacks that run after the HTTP response has been returned.
BaseController
Base class for all DartAPI controllers.
DartAPI
Central application class — configure middleware, register controllers, and call start to bind the HTTP server.
DartApiTestClient
In-process HTTP test client — calls a Shelf Handler directly without opening a TCP socket.
DocsController
A BaseController that serves OpenAPI documentation endpoints.
EmailValidator
Validates that a string matches a valid email format.
EnumValidator<T>
Validates that a value is one of the allowed values.
EnvConfig
Base class for typed, environment-variable-backed configuration.
Field<T>
Describes a single field in a FieldSet: its expected Dart type, whether it is required, and any validators that should run against its value.
FieldSet
A declarative set of typed, validated fields that derives both runtime validation and an OpenAPI JSON Schema from a single declaration.
HealthCheckResult
Result of a named health check supplied to HealthController.
HealthController
A minimal controller that exposes GET /health.
InlineController
A BaseController that takes its routes as a constructor argument.
InMemoryTokenStore
An in-memory implementation of TokenStore.
JwtService
Service for generating and verifying JWTs.
MaxLengthValidator
Validates that a string has at most max characters.
MetricsController
Exposes GET /metrics in Prometheus text format (0.0.4).
MetricsRegistry
Singleton registry that accumulates Prometheus-compatible metrics for every request recorded by metricsMiddleware.
MinLengthValidator
Validates that a string has at least min characters.
NotEmptyValidator
Validates that a string is not blank (empty or whitespace-only).
OpenApiGenerator
Generates an OpenAPI 3.0 specification from a list of ApiRoutes.
PaginatedResponse
A generic paginated response wrapper that implements Serializable.
Pagination
Extracts page and limit query parameters from a request and computes offset.
PatternValidator
Validates that a string matches the given pattern.
QueryParamSpec
Describes a single query parameter for OpenAPI documentation.
RangeValidator<T extends num>
Validates that a number falls within an optional min and max range (inclusive).
RouterManager
Registers BaseController instances with a Shelf Router and collects all ApiRoutes for OpenAPI generation.
Serializable
An abstract interface for objects that can be converted to JSON.
ServiceRegistry
A simple, type-safe service locator with lazy-singleton instantiation and circular dependency detection.
SseEvent
A single Server-Sent Event.
TestResponse
An HTTP response returned by DartApiTestClient.
TokenStore
Interface for tracking revoked JWT tokens.
UploadedFile
Represents a single file or field from a multipart/form-data request.
UrlValidator
Validates that a string is a well-formed absolute URL (http or https).
Validators<T>
An abstract class for validating values of type T.
WebSocketRoute
A WebSocket endpoint that can be registered alongside ApiRoutes in a BaseController.

Enums

ApiMethod
Represents supported HTTP methods for an API route.
AppEnvironment
The active runtime environment.
LogFormat
Output format for loggingMiddleware.
SecurityScheme
Defines security schemes that can be applied to an ApiRoute.

Extensions

BackgroundTaskExtension on Request
Convenience extension so handlers can schedule tasks without casting.
CookieRequestExtensions on Request
MapExtensions on Map<String, dynamic>
Extension methods on Map<String, dynamic> for typed, validated key extraction.
MultipartExtensions on Request
Multipart / file-upload helpers on Shelf's Request.
RequestExtensions on Request
Extension methods on Shelf's Request for typed path and query parameter extraction.
TokenHelpers on Map<String, String>
Header parsing helpers for auth middleware.

Functions

apiKeyMiddleware({required Set<String> validKeys, String headerName = 'X-API-Key'}) → Middleware
Shelf middleware that validates API keys from a request header.
authMiddleware(JwtService jwtService) → Middleware
Middleware to protect routes using JWT Bearer token authentication.
backgroundTaskMiddleware() → Middleware
Middleware that enables BackgroundTaskQueue for every request.
bodySizeLimitMiddleware({int maxBytes = 1024 * 1024}) → Middleware
Rejects requests whose Content-Length exceeds maxBytes.
cacheMiddleware({Duration ttl = const Duration(minutes: 5), int maxEntries = 500, String keyExtractor(Request)?}) → Middleware
In-memory response cache middleware for GET requests.
compressionMiddleware({int threshold = 1024}) → Middleware
Middleware that gzip-compresses response bodies when the client supports it.
globalExceptionMiddleware({required ApiException onError(Object error, StackTrace stackTrace)}) → Middleware
A middleware that catches any unhandled exception from downstream handlers and delegates to onError to produce a custom ApiException.
loadEnvFile(String path) Map<String, String>
Parses a .env file into a Map<String, String>.
loggingMiddleware({LogFormat format = LogFormat.text, List<String> excludePaths = const []}) → Middleware
Logs every request in the chosen format (default: LogFormat.text).
mergeEnv(List<Map<String, String>> sources) Map<String, String>
Merges env maps in order — later maps override earlier ones. Platform.environment is always applied last so real process environment variables always take the highest priority.
metricsMiddleware() → Middleware
Records http_requests_total and http_request_duration_seconds for every request passing through the pipeline.
rateLimitMiddleware({int maxRequests = 100, Duration window = const Duration(minutes: 1), String keyExtractor(Request)?}) → Middleware
Token-bucket rate limiter middleware.
requestIdMiddleware({String headerName = 'X-Request-Id'}) → Middleware
Middleware that attaches a unique X-Request-Id header to every request/response pair.
securityHeadersMiddleware({String xFrameOptions = 'DENY', String xContentTypeOptions = 'nosniff', String referrerPolicy = 'strict-origin-when-cross-origin', String xXssProtection = '1; mode=block', String permissionsPolicy = 'camera=(), microphone=(), geolocation=()', String? contentSecurityPolicy, String? strictTransportSecurity}) → Middleware
Adds common security headers to every response.
setCookie(Response response, String name, String value, {Duration? maxAge, String? path, String? domain, String? sameSite, bool httpOnly = false, bool secure = false}) → Response
Adds a Set-Cookie header to response.
sseResponse(Stream<SseEvent> events) → Response
Returns a Shelf Response that streams events as Server-Sent Events.
timeoutMiddleware(Duration timeout) → Middleware
Middleware that returns 408 if the inner handler does not respond within timeout.
toOpenApiPath(String path) String
Converts a shelf_router path (e.g. /users/<id>) to OpenAPI format (/users/{id}).

Exceptions / Errors

ApiException
An exception that carries an HTTP status code and message.
InvalidEnvException
Thrown when an environment variable cannot be parsed to the expected type.
MissingEnvException
Thrown when a required environment variable is missing.
ValidationException
Thrown when one or more request fields fail validation.