http library
Requests, responses, middleware, routing, resources and the server engine.
A subset of package:daravel/daravel.dart for files that need only this
area, or whose own names collide with the full barrel (JwtException,
UniqueRule, ModelNotFoundException, CorsMiddleware, ...).
Classes
- AlgorithmRateLimitStore
- A RateLimitStore that also counts with other algorithms than the fixed window (Limit.slidingWindow, Limit.gcra).
- BodyLimitsMiddleware
- Request body limits (BLUEPRINT_V2 §2.3). Defaults: 1 MiB for JSON and form bodies, 50 MiB for multipart/other bodies, JSON nesting ≤ 64.
- BytesBody
- CacheHeadersMiddleware
-
Laravel's
cache.headersmiddleware (SetCacheHeaders): - Cidr
-
An IPv4/IPv6 network in CIDR notation (
10.0.0.0/8,::1/128) or a single address. - ClientRequest
- An outgoing request, as sent (and as recorded by HttpFake).
- ClientResponse
-
A response to an outgoing request (Laravel's
Http\Client\Response). - CompressResponseMiddleware
-
Compresses responses with gzip for clients that accept it
(
Accept-Encoding: gzip): bodies of at least minLength bytes with a compressible type (JSON, text, XML, SVG, JavaScript). Streams (server-sent events, downloads) are left alone. A strongETagbecomes weak, as the bytes change with the encoding. - ConvertEmptyStringsToNullMiddleware
-
Converts empty string inputs to
null(Laravel'sConvertEmptyStringsToNull). - CorsConfig
-
CORS configuration (
config/cors.phpparity). - CorsMiddleware
-
Cross-origin resource sharing. Secure by default: no origin is allowed
until configured, and
*is never combined with credentials (BLUEPRINT_V2 §9.2). - EmptyBody
- ExceptionHandler
- Central exception → response mapping (ADR-009).
- FunctionalMiddleware
- Middleware backed by a closure.
- Headers
- Case-insensitive, multi-value HTTP header collection.
- Http
-
Outgoing HTTP requests, like Laravel's
Httpfacade: - HttpClientFactory
-
Sends outgoing requests (one pooled
dart:ioclient) or answers them from a fake. Registered as a singleton in the application container. - HttpFake
-
Stubs and the requests sent while faking (
Http.fake()). - HttpKernel
- Orchestrates the request lifecycle (BLUEPRINT_V2 §5.4): global middleware → routing → route middleware → handler → response conversion, with exception rendering at both the route and global layers, per-route timeouts and a terminate phase after the response is sent.
-
JsonResource<
T> -
Transforms a value (usually a Model) into its API representation
(Laravel
JsonResource; BLUEPRINT_V2 §7.10.5). - JsonSerializable
- Objects that provide a JSON representation.
- Limit
-
A rate limit (Laravel
Illuminate\Cache\RateLimiting\Limit). - MaintenanceMode
-
Maintenance mode state in
storage/framework/down, the file and JSON shape Laravel'sphp artisan downwrites (dartisan down/up). - MemoryRateLimitStore
-
Fixed-window counters in this isolate's memory, like Laravel's
RateLimiter(hits + reset time per key): O(1) time and two integers per key, whatever the limit. - MergeValue
-
Attributes merged into the parent map (
mergeWhen). - Middleware
- Onion-style middleware (BLUEPRINT_V2 §7.2.4).
- MiddlewarePipeline
- Runs a list of middleware around a core handler.
- MiddlewareRegistry
-
Global middleware stack, aliases, groups and priority, configured via
ApplicationBuilder.withMiddleware. - MissingValue
-
Marker for attributes omitted by
when/whenLoaded(LaravelMissingValue). - MultipartLimits
-
Limits applied while parsing (PHP's
max_input_vars,max_file_uploads; the total size is the request's body limit). - PendingRequest
-
A request being configured (Laravel's
PendingRequest). - PreventRequestsDuringMaintenance
-
Answers 503 while the application is in maintenance mode, like Laravel's
PreventRequestsDuringMaintenance. - ProcessRateLimitStore
- Process-wide counters via the coordinator. Fails open on coordinator errors/timeouts (the request is allowed and onError is notified), the documented default for rate limiting (§5.2).
-
RadixTree<
T extends Object> - Segment-based route tree with static > parameter > wildcard priority and backtracking (BLUEPRINT_V2 §7.3.1).
- RateLimiter
-
Named limiters + counters (Laravel
RateLimiter; BLUEPRINT_V2 §7.7). - RateLimitGrant
- Grant of MemoryRateLimitStore.acquireSync: how many of the requested hits were recorded and the window they belong to.
- RateLimitResult
- Outcome of RateLimitStore.attempt.
- RateLimitService
- Coordinator service exposing a MemoryRateLimitStore to every worker.
- RateLimitStore
- Backing store of attempt counters (ADR-003 scopes).
- Request
- Incoming HTTP request (BLUEPRINT_V2 §7.2.2).
- RequestIdMiddleware
-
Echoes the request id as
x-request-idon every response. -
ResourceCollection<
T> -
A collection of resources; paginators add Laravel's
linksandmeta. - ResourceController
-
Controller contract for
Router.apiResource(index, store, show, update, destroy). Implement the actions you need; the router only registers the ones selected withonly/except. - ResourceWrapping
-
Shape of a resource payload: the wrapping key (
data) is global, like Laravel'sJsonResource::$wrap. - Responsable
- Objects that know how to turn themselves into a Response.
- Response
- Immutable HTTP response (BLUEPRINT_V2 §7.2.3).
- ResponseBody
- Body of a Response.
- ResponseSequence
- Responses handed out in order by one stub.
- RouteEntry
- A registered route with fluent configuration (BLUEPRINT_V2 §7.3.2).
-
RouteMatch<
T extends Object> - Result of a successful RadixTree.lookup.
- RoutePatterns
-
Well-known parameter patterns (Laravel
whereNumber,whereUuid, ...). - Router
- Fluent router (BLUEPRINT_V2 §7.3.2). Routes are registered during boot and compiled once into per-method RadixTrees.
- RouteResponse
- A documented route response (see RouteEntry.returns).
- SecurityHeadersMiddleware
- Conservative security headers for API responses (BLUEPRINT_V2 §9.2). Headers already set by the handler are preserved.
- ServeOptions
- Options for Application.serve.
- ServerEngine
-
Binds the
dart:ioserver, wraps every request in a request scope and performs graceful shutdown onSIGINT(andSIGTERMoutside Windows). - SetLocaleMiddleware
-
Picks the request's locale from
?lang=(or query) or theAccept-Languageheader, among supported, and makes it the locale of the request: trans,App.localeand validation messages follow it. Without a match the application locale stays. - SseEvent
-
One server-sent event (Laravel's
StreamedEvent): event defaults toupdateas in Laravel'sresponse()->eventStream(); data that is not a string or number is sent as JSON. - StreamBody
- TerminableMiddleware
-
Middleware with work to do after the response has been sent to the
client (Laravel's
terminate()), such as flushing logs or metrics. - ThrottleMiddleware
-
throttle:60,1(max attempts, decay minutes) orthrottle:api(named limiter). AddsX-RateLimit-Limit/X-RateLimit-Remainingto responses and answers 429 withRetry-Afterwhen exceeded. - TrimStringsMiddleware
-
Trims surrounding whitespace from every string input, except the keys
listed in except (Laravel's
TrimStrings, which skips passwords). - TrustProxiesMiddleware
-
Applies
X-Forwarded-*headers only when the TCP peer is a trusted proxy (BLUEPRINT_V2 §2.3, §9.1). Without this middleware, or when the peer is not trusted, forwarded headers are ignored andrequest.ipis the socket address, which makes IP-based rate limiting unspoofable. - UploadedFile
-
A file sent in a
multipart/form-datarequest (Laravel'sIlluminate\Http\UploadedFile). - UploadedFileFactory
-
UploadedFile.fakehelpers. - UpstreamProxy
- Forwards requests Daravel has no route for to another server, usually the Laravel application being migrated (the strangler fig pattern, Blueprint #29): migrated routes answer from Daravel, the rest from Laravel, behind one address, on one database.
- UrlSigner
-
Signs and verifies URLs with HMAC-SHA256 (Laravel
URL::signedRoute). - ValidateSignatureMiddleware
-
Rejects requests whose URL signature is missing, invalid or expired
(
signedmiddleware alias; LaravelValidateSignature). - WebResourceController
-
Adds the HTML form actions used by
Router.resource(create, edit).
Enums
- ForwardedHeader
- Forwarded headers that a trusted proxy may supply.
- RateLimitAlgorithm
- How a Limit counts attempts.
- ResponseShape
- How a route returns its item schema (see RouteEntry.returns).
Constants
- missing → const MissingValue
- The single MissingValue instance.
-
reasonPhrases
→ const Map<
int, String> - Standard reason phrases used when aborting without a custom message.
Functions
-
abort(
int status, [String? message, Map< String, String> headers = const <String, String>{}]) → Never -
Throws an HttpException with
status(Laravel'sabort()helper). -
abortIf(
bool condition, int status, [String? message, Map< String, String> headers = const <String, String>{}]) → void -
Aborts with
statuswhenconditionis true (abort_if()). -
abortUnless(
bool condition, int status, [String? message, Map< String, String> headers = const <String, String>{}]) → void -
Aborts with
statusunlessconditionis true (abort_unless()). -
buildInput(
Iterable< (String, Object)> pairs, {int maxDepth = 32}) → Map<String, Object?> -
Nests
name[key][]-stylepairsinto maps and lists, as PHP fills$_GET,$_POSTand$_FILES(used for query strings, form bodies and multipart fields and files). -
buildOpenApi(
Iterable< RouteEntry> routes, {String title = 'Daravel API', String version = '1.0.0', String? serverUrl}) → Map<String, Object?> -
Builds an OpenAPI 3.1 document from the compiled route table
(
dartisan openapi:generate, the live/docs/apipage). -
detectMimeType(
List< int> header) → String -
Detects a MIME type from the first bytes of a file, never from its name:
package:mimesignatures plus BMP, SVG, ZIP-based documents (Office Open XML, OpenDocument) and plain text. -
extensionForMimeType(
String mimeType) → String? -
The usual extension for
mimeType(Symfony'sguessExtension). -
isolateSizingAdvice(
{required bool production, required int isolates, int? processors}) → String? -
Why a production server with one HTTP isolate on a machine with several
cores may be undersized, or
nullwhen it is not the case: one isolate runs one CPU-bound request at a time, so heavy endpoints stop scaling with concurrency.servelogs it anddartisan doctorreports it. -
isWebSocketUpgrade(
Request request) → bool -
Whether
requestasks to switch to the WebSocket protocol. -
laravelErrorResponse(
Map< String, Object?> body, {required int status, Map<String, String> headers = const <String, String>{}}) → Response -
Laravel's
Handler::prepareJsonResponsebody: the error as JSON withJSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES(four-space indent,/kept, non-ASCII as `` escapes), as Laravel 8 to 13 send every error but 401Unauthenticated.and 422 validation errors. -
multipartBoundary(
String? contentType) → String? -
The boundary of a
multipart/form-datacontent type, ornull. -
parseQueryString(
String query, {int maxDepth = 32}) → Map< String, Object?> -
Parses a query string (or form body) the way PHP's
parse_strfills Laravel's input:a[]=1&a[]=2is a list,f[status]=xa map, keys nest up tomaxDepthlevels, and a repeated plain key keeps its last value. Maps whose keys are exactly0..n-1become lists, as in Laravel's JSON. -
singularize(
String word) → String -
Minimal English singularization used for resource parameter names
(
posts→post,categories→category,people→people). -
sseStream(
Stream< Object?> events, {Object? endStreamWith = '</stream>', Duration? heartbeat = const Duration(seconds: 15)}) → Stream<List< int> > -
The body of
Response.sse:events(each an SseEvent or a value sent as anupdateevent), a heartbeat comment everyheartbeatwhile idle, thenendStreamWith(Laravel's</stream>,nullfor none). Ends early when the application starts draining; cancelling (the client went away) cancelsevents.
Typedefs
-
ExceptionRenderer<
T extends Object> = FutureOr< Response?> Function(T exception, Request request) -
Renders an exception of type
Tinto a Response, or returnsnullto fall through to the next renderer. It may be asynchronous: write an audit row, read a translation, encrypt the body. -
ExceptionReporter<
T extends Object> = FutureOr< void> Function(T exception, StackTrace stackTrace, Request request) -
Reports (logs, forwards) an exception of type
T. -
Handler
= FutureOr<
Object?> Function(Request request) -
A route handler. May return a
Response, aResponsable, a JSON-able value (Map,List,num,bool,JsonSerializable), aString(text) ornull(empty 200). - InputTransformer = Object? Function(String key, Object? value)
-
Rewrites an input value; used by
TrimStringsandConvertEmptyStringsToNullstyle middleware. -
LimitResolver
= FutureOr<
Object?> Function(Request request) -
Resolves the limit(s) for a request: a Limit, a
List<Limit>ornull(no limit). -
MatchPredicate<
T extends Object> = bool Function(T value, Map< String, String> params) -
Decides whether
valueaccepts the capturedparams(route constraints). -
MiddlewareFactory
= Middleware Function(List<
String> params) -
Builds a middleware from alias parameters (
'throttle:60,1'→[60, 1]). -
Next
= Future<
Response> Function(Request request) -
Continues the pipeline with
requestand yields the downstream response. -
RouteBinder
= FutureOr<
Object?> Function(String value, Request request) -
Resolves a route parameter value into a bound object (
null→ 404 when Router.bind was registered withorFail). -
ThrottleResponseBuilder
= Response Function(Request request, Map<
String, String> headers) -
Builds the 429 response for a limit (
Limit.response). -
WebSocketHandler
= FutureOr<
void> Function(WebSocket socket, Request request) -
Handles an upgraded connection (
router.ws).
Exceptions / Errors
- BadRequestHttpException
- ConnectionException
- The server could not be reached, or did not answer in time.
- ForbiddenHttpException
- HttpException
- An exception that maps directly to an HTTP response (ADR-009).
- MethodNotAllowedHttpException
- NotFoundHttpException
- PayloadTooLargeHttpException
- RequestException
- A 4xx or 5xx response, thrown by ClientResponse.throwIfFailed.
- StrayRequestException
- A request that matched no stub while stray requests are prevented.
- ThrottleRequestsException
-
429 with
Retry-AfterandX-RateLimit-*headers.