dartapi_core 0.1.7
dartapi_core: ^0.1.7 copied to clipboard
Core utilities for building typed, structured REST APIs in Dart, including routing, validation, and middleware support.
0.1.7 #
Milestone 5 — OpenAPI Tags.
- Add
tagsfield toApiRoute— aList<String>that appears undertagsin the generated OpenAPI operation object. Routes with the same tag are grouped together in Swagger UI and ReDoc. - Add
withTags(List<String>)method toApiRoute— returns a copy of the route with new tags (all other fields unchanged). Used internally byRouterManager. - Add
taggetter toBaseController— override in a subclass to automatically apply one tag to every route that declares no explicit tags (e.g.String? get tag => 'Users';). Routes that already have explicit tags are not affected. - Update
RouterManager.registerController()— stamps the controller'stagonto routes with an emptytagslist before collecting them for the spec generator. - Add
tagDescriptionsparameter toOpenApiGenerator,DocsController, andenableDocs()— aMap<String, String>of tag name → description. These appear in the top-leveltagsarray of the OpenAPI spec, adding human-readable descriptions under each group heading in Swagger UI and ReDoc. OpenApiGenerator.generate()now emitstagson each operation when the route has tags and a deduplicated top-leveltagsarray (with optional descriptions) when any route ortagDescriptionsentry declares a tag.- Update
rest_apiexample —BookControlleroverridestag => 'Books';enableDocs()passestagDescriptions: {'Books': 'CRUD operations for the book catalogue'}. - 21 new tests in
test/openapi_tags_test.dart(566 total).
0.1.6 #
Milestone 3 — Example Projects.
- Add
example/minimal/— one-file server withInlineController, health check, and Swagger UI; compiles to a standalone executable. - Add
example/rest_api/— full CRUD Books API:FieldSetDTOs, JWT auth,ServiceRegistry,QueryParamSpec,$refschemas,DartApiTestClienttests (14 tests). Demonstrates every Milestone 1–2 feature end-to-end. - Add
example/standalone_no_cli/— annotated starter project equivalent todartapi create --minimal; explains every file and every decision. - Add
schemasparameter toenableDocs()— passMap<String, Map<String, dynamic>>of named schemas; forwarded toDocsControllerandOpenApiGeneratorsocomponents/schemasappears in the spec without constructing the generator manually. - Add
schemasfield toDocsController— enables named schemas when constructing the controller directly withoutDartAPI. - Update
README.md— lead with "Getting Started in 5 Minutes (No CLI)", examples table, updated validators table withEnumValidator,QueryParamSpecand$refOpenAPI docs.
0.1.5 #
Milestone 2 — OpenAPI Spec Quality.
- Add
QueryParamSpec— describes a query parameter for OpenAPI docs (name,type,required,description,defaultValue). Export from barrel. - Add
queryParamsfield toApiRoute— acceptsList<QueryParamSpec>. Query params now appear underparameterswithin: queryin the generated spec alongside path params. - Add
schemasparameter toOpenApiGenerator— aMap<String, Map<String, dynamic>>of named schemas emitted undercomponents/schemas. Routes can reference them with{'\$ref': '#/components/schemas/Name'}. - Add
EnumValidator<T>(List<T> values)— validates a closed value set;toSchemaProperties()emits{enum: [...]}. Export from barrel. - Add array type support to
Field<T>:Field<List<String>>/Field<List<int>>/ etc. now producejsonType: 'array'.- New
arrayItemTypeproperty auto-derived from the generic element type. FieldSet.toJsonSchema()emitsitems: {type: ...}for array fields.
- 30 new tests in
test/openapi_spec_quality_test.dart(545 total).
0.1.4 #
Milestone 1 — Schema-Validation Sync (FieldSet).
- Add
Field<T>— describes a single DTO field: Dart type (mapped to JSON Schematype),requiredflag, validators list, optionalexampleanddescription. - Add
FieldSet— a declarative map ofFields that provides:validate(Map<String, dynamic> json)— collects ALL field errors before throwing a singleValidationException, replacing the need for manualvalidateAllboilerplate.toJsonSchema()— derives a complete OpenAPI-compatible JSON Schema (type: object,properties,requiredarray,nullablefor optional fields) directly from the field declarations.
- Add
toSchemaProperties()to every built-in validator so schema constraints come from the same source as validation rules:EmailValidator→{format: email}. Constructor message is now optional (default:'Invalid email address').MinLengthValidator(n)→{minLength: n}MaxLengthValidator(n)→{maxLength: n}NotEmptyValidator→{minLength: 1}RangeValidator(min, max)→{minimum, maximum}PatternValidator→{pattern}UrlValidator→{format: uri}
- Export
FieldandFieldSetfrom thedartapi_corebarrel. - 37 new tests in
test/field_set_test.dart(515 total).
0.1.3 #
- Add comprehensive Books API example (
example/dartapi_core_example.dart) demonstratingDartAPI,ServiceRegistry,JwtService,authMiddleware,InMemoryTokenStore,BaseController,ApiRoute,InlineController,Pagination,PaginatedResponse,ApiException, background tasks, per-route caching, health check, Prometheus metrics, and Swagger UI — all in a single runnable file.
0.1.2 #
Milestone 4 — dependency injection via ServiceRegistry.
- Add
ServiceRegistry— type-safe service locator with lazy-singleton instantiation and circular dependency detection.register<T>(T Function(ServiceRegistry))— lazy singleton factory; factory receives the registry to resolve sub-deps.registerSingleton<T>(T instance)— eager singleton (pre-built instance).get<T>()— resolves and caches on first call; throwsStateErrorfor unregistered types or circular deps.isRegistered<T>(),unregister<T>(),clear().- Circular dependency detected at resolution time with a full chain in the error message (e.g.
A → B → A). - Registry is usable again after catching a circular dependency error.
- Wire
ServiceRegistryintoDartAPI— convenience methodsapp.register<T>(),app.registerSingleton<T>(),app.get<T>(),app.isRegistered<T>(),app.registry. - 43 new tests in
test/service_registry_test.dartcovering all registration modes, error paths, circular deps, type safety, andDartAPIintegration. - Full suite: 478 tests passing.
0.1.1 #
Milestone 2 — auth merged in.
- Merge all of
dartapi_authintodartapi_core/lib/src/auth/:JwtService(HS256 + RS256),authMiddleware,apiKeyMiddleware,TokenStore,InMemoryTokenStore,TokenHelpers. - Add
dart_jsonwebtoken ^3.4.1as a package dependency. - Add 70 tests in
test/auth_test.dartcoveringInMemoryTokenStore,JwtService(HS256 + RS256, revocation, rotation, JTI uniqueness),authMiddleware,apiKeyMiddleware, andTokenHelpers.
0.1.0 #
Framework extraction (Milestone 1) — dartapi_core is now a standalone framework.
- Add
DartAPIclass — the central application class with opt-in middleware (enableCompression,enableBackgroundTasks,enableTimeout,enableRateLimit,enableMetrics,enableHealthCheck,enableDocs) and lifecycle hooks (onStartup,onShutdown). No longer requires the CLI to use. - Add
RouterManager— registersBaseControllerinstances with a ShelfRouter; collects allApiRoutes for OpenAPI generation. - Add
InlineController— define routes inline without creating a dedicated controller class. - Add
AppConfig— convenienceEnvConfigsubclass with common fields (port, debug, logLevel, database, JWT, CORS); extend to add project-specific fields. - Add
loadEnvFile/mergeEnv—.envfile parsing utilities. - Add
shelf_routerandshelf_cors_headersas package dependencies.
0.0.27 #
- Upgrade
lintsfrom^5.0.0to^6.1.0; fixunnecessary_underscoreslint in tests (__→_)
0.0.26 #
- Fix
compressionMiddleware: responses below the compression threshold had their body stream silently consumed and then returned unmodified — shelf would throw "read method can only be called once" when it tried to send the response. Now rebuilds the response with the already-buffered bytes viaresponse.change(body: bytes).
0.0.25 #
ApiRoutehandler now passes pre-builtshelf.Responseobjects through unchanged — enables SSE (sseResponse()) and file-download handlers to be used withtypedHandler
0.0.24 #
- Add
DartApiTestClient— in-process test client that calls a ShelfHandlerdirectly (no TCP socket); exposesget,post,put,delete,patchandTestResponsewith.json<T>() - Add
LogFormatenum (text|json) tologgingMiddleware— JSON mode emits structured log lines withtimestamp,level,method,path,status,duration_ms, andrequest_id(whenrequestIdMiddlewarehas run) - Add
metricsMiddleware()— recordshttp_requests_totalandhttp_request_duration_secondshistograms per(method, path, status)in a singletonMetricsRegistry - Add
MetricsController— exposesGET /metricsin Prometheus text format (0.0.4); register viaapp.enableMetrics()
0.0.23 #
- Add
cacheTtl: Duration?toApiRoute— opt-in per-route response caching without touching global middleware - Add
ApiRoute.effectiveMiddlewaresgetter — returns[cacheMiddleware(ttl: cacheTtl), ...middlewares]whencacheTtlis set; used byRouterManager - Update
cacheMiddlewaredocstring with per-route usage examples
0.0.22 #
- Add
ValidationException— carries a list of{field, message}errors for multi-field validation failures - Add
Map.validateAll(fields)— runs all field validations, collects every failure, then throwsValidationExceptionwith the full list (instead of stopping at the first error) ApiRoutehandler now catchesValidationExceptionbeforeApiExceptionand returns{"errors": [...]}with status 422
0.0.21 #
- Add
timeoutMiddleware(Duration)— returns 408 if handler exceeds the timeout - Fix:
nullhandler result now returns 204 No Content instead of throwing a 500 - Improve
loggingMiddlewareoutput:[timestamp] METHOD /path STATUS 12ms— removed emoji, added response duration
0.0.20 #
- Fix:
_serializenow handlesboolandnumresponses — returning aboolfrom a handler no longer throws a 500 "Unable to serialize" error
0.0.19 #
- Add
test/base_controller_test.dart— routes getter, webSocketRoutes default, route callability - Add
test/logging_middleware_test.dart— pass-through behaviour, method coverage, pipeline composition - Extend
test/api_route_test.dart— per-route middleware: ordering, short-circuit, header injection
0.0.18 #
- Add
EnvConfigbase class — typed env var access (env,envInt,envDouble,envBool) with injectableenvironmentmap for testing - Add
MissingEnvExceptionandInvalidEnvException - Add
HealthController— exposesGET /healthreturning{"status":"ok","uptime":"..."}
0.0.17 #
- Fix: use super parameters in
NotEmptyValidatorandUrlValidator(linter cleanup)
0.0.16 #
- Add
MinLengthValidator,MaxLengthValidator,NotEmptyValidator,RangeValidator<T extends num>,PatternValidator,UrlValidator - Add
Pagination— extracts?pageand?limitfrom a request with clamping; computesoffset - Add
PaginatedResponse—Serializablewrapper that includes ametablock (page,limit,total,totalPages,hasNext,hasPrev) - Add
SseEventandsseResponse()for Server-Sent Events streaming
0.0.15 #
- Add
header<T>()extension onRequestfor typed header extraction (case-insensitive) - Add
CookieRequestExtensions—request.cookiesmap andrequest.cookie(name)for reading cookies - Add
setCookie()helper for attachingSet-Cookieheaders to responses (supportsmaxAge,path,domain,sameSite,httpOnly,secure) - Add
cacheMiddleware— in-memory GET response cache with configurable TTL and custom key extractor; addsX-Cache: HIT/MISSheaders
0.0.14 #
- Add
multipartFiles(),file(),formFields()extensions onRequestformultipart/form-dataparsing - Add
UploadedFilewithbytes,filename,contentType,text, andisFile - Add
BackgroundTaskQueue,backgroundTaskMiddleware(), andRequest.backgroundTasksfor post-response async work - Add
WebSocketRoutefor WebSocket endpoints alongside HTTP routes BaseControllernow haswebSocketRoutes(default empty list)- New dependencies:
mime,shelf_web_socket,web_socket_channel
0.0.13 #
- Add
rateLimitMiddleware— token-bucket rate limiter keyed by IP (or custom key); returns 429 withRetry-AfterandX-RateLimit-*headers - Add
requestIdMiddleware— attachesX-Request-Idto every request/response; propagates existing IDs; stores ID inrequest.context['requestId'] - Add
compressionMiddleware— gzip-compresses responses above a configurable threshold when client sendsAccept-Encoding: gzip
0.0.12 #
- Improve README: update version snippet, improve formatting
0.0.11 #
- Fix type-mismatch error message in
verifyKey: now uses friendly JSON type names (string,integer,number,boolean) instead of Dart type names
0.0.10 #
- Swagger UI:
bearerAuthsecurity scheme is now always present in the spec so the Authorize button always appears - Swagger UI:
persistAuthorization: true— entered tokens survive page refreshes (stored in localStorage)
0.0.9 #
- Add
OpenApiGenerator— generates an OpenAPI 3.0 spec from a list ofApiRoutes - Add
DocsController— servesGET /openapi.json,GET /docs(Swagger UI),GET /redoc(ReDoc) - Add
SecuritySchemeenum withbearervalue;ApiRoutenow acceptssecurity: [SecurityScheme.bearer] - Add
contentTypefield onApiRoute(default'application/json'); used for HTML doc routes - Add tests for all new OpenAPI types (23 additional tests)
0.0.8 #
- Expand test suite: comprehensive tests for
ApiRoute,RequestExtensions(pathParam/queryParam),MapExtensions, andglobalExceptionMiddleware
0.0.7 #
- Add
pathParam<T>()extension onRequestfor typed path parameter extraction - Add
queryParam<T>()extension onRequestfor typed query parameter extraction with optional default values - Add
statusCodefield onApiRoute(default200) for custom success response codes (e.g. 201, 204) - Add
globalExceptionMiddlewarefor app-level exception handling
0.0.6 #
- Add
ApiExceptionclass for returning specific HTTP error status codes from handlers and validators - Fix
FormatException(malformed JSON body) now returns 400 Bad Request instead of 500 - Fix validation errors from
verifyKey()now return 422 Unprocessable Entity instead of 500 ApiExceptionis exported from the package
0.0.5 #
- Improved Logging
0.0.4 #
- Improve code documentation
0.0.3 #
- Add Email Validator
0.0.2 #
- Change License
- Add Middelware
- Add Validators
- Enhance Key Verification with Validators
0.0.1 #
- Initial version.