baaba_api_handler 5.0.0
baaba_api_handler: ^5.0.0 copied to clipboard
A typed, functional HTTP client for Flutter. Wraps Dio with Either-based error handling, token refresh, retries, request de-duplication, and a built-in test double.
5.0.0 #
Major because of one new error case, certificateRejected: code that switches exhaustively over ErrorSource or ResponseCode needs a case for it. Everything else is new API, fixes, or behaviour changes most apps need no code for (see Changed). Upgrade steps are in MIGRATION.md.
⚠️ Breaking changes #
- A refused TLS certificate has its own error:
ErrorSource.certificateRejected/ResponseCode.certificateRejected(-10). It used to beconnectionFailure("Failed to connect to the server") when Dio flagged the certificate, anddefaultErrorwhen — as with Dio's default adapter on mobile and desktop — the failed handshake escaped as anunknownerror; neither could be told apart from an ordinary network failure. Exhaustive switches need a case for it. Code that treatedconnectionFailureas "maybe a bad certificate" should match the new value. - Every
ApiServicesrequest method gainedretryableandextraparameters (see Added). Calling code is unaffected. A class that implementsApiServicesby hand must add them to its overrides;FakeApiServicesand mocktail mocks need nothing.
Added #
ApiEndpoint. A path template with{}placeholders —ApiEndpoint('orders/{}/attachments/{}').fill([id, name])— filled in order, each argument URL-encoded as a single path segment. ThrowsArgumentErroron a count mismatch, or for an empty,.or..argument. An extension type overString, so it costs nothing at runtime and passes anywhere an endpoint does.- Generated endpoints and environments:
@BaabaApiEndpoint,@BaabaApiEnvironment,@BaabaApiField, read by the new dev dependencybaaba_api_generator. It turnsKEY=valuelines in the app's.envfiles into typed members —Endpoints.updateOrder(orderId)fororders/{orderId}, typedint/bool/Uriconfiguration — obfuscated by default and checked at build time. Replacesenviedplus a hand-written wrapper per endpoint; existingenvied.envfiles work unchanged. The annotations,ApiEndpoint, and the@internalruntime decoder generated code calls are also available from the Flutter-freepackage:baaba_api_handler/annotations.dart, which the generator imports. Addsmetaas a direct dependency (already pinned by Flutter). - Certificate pinning:
ApiConfig.pinning/PinningConfig. Trusts each host only if its certificate chains to the PEM roots listed for it, matched exactly or by*.suffix. Each set of roots gets its ownHttpClientonSecurityContext(withTrustedRoots: false), with nobadCertificateCallback, so a certificate that does not chain fails the TLS handshake. Unlisted hosts use the system trust store, or are refused withUnlistedHostPolicy.refuse. Redirects are followed hop by hop, each checked against its own host's pins and the unlisted-host policy; plainhttp://to a pinned host is refused. Host matching ignores a trailing dot (api.example.com.), and an IPv6 key may be written with or without brackets. A rejection isErrorSource.certificateRejectedand is not retried. Ignored on web, where the browser owns TLS; selected through a conditional import, so the core library stays web-safe. - Proxy for selected hosts:
ApiConfig.proxy/ProxyConfig. Routes requests for the listed hosts (exact or*.suffix) throughhost:portand everything elseDIRECT, viaHttpClient.findProxy. Works with pinning:httpsis tunnelled withCONNECTand the certificate is still verified against the pinned roots. Anullproxy sends everything direct. Ignored on web. package:baaba_api_handler/io.dart.pinnedHttpClient(roots)(adart:ioHttpClient, e.g. forIOWebSocketChannel.connect(customClient: ...)) andpinnedIoClient(roots)(apackage:httpIOClient, e.g. for SignalR) trust the same roots outside Dio, and take the sameproxy:. Mobile and desktop only. Addshttpas a direct dependency — it was already a transitive one throughinternet_connection_checker_plus.retryableandextraon every request method, including the*As<T>variants,head,options,uploadanddownload.retryable: truelets one call be retried as if idempotent — a read-onlyPOST, such as a GraphQL query — still withinmaxRetries,retryableStatusCodesandretryIf;falsenever retries it, not even on429/503.extrais copied intoRequestOptions.extraforretryIf, interceptors and the observer; the flag is there too, under the newRetryPolicy.retryableKey. Both are part of the de-duplication key, andRecordedCallgainsretryableandextra.- Log redaction, on by default. Masks the
Authorizationheader and those inApiLogOptions.redactHeaders(cookie,set-cookie,x-api-key, …), query parameters inredactQueryParams(includingt, as realtime hubs pass the token) whether inparamsor the endpoint, and body fields inredactBodyFields(password,token,accessToken,refreshToken, …) at any depth in request and response bodies — JSON, form-urlencoded strings andFormData— plus secret query parameters in redirect locations. A masked header, query parameter or token field keeps its firstredactKeepChars(4) characters:Bearer eyJh…[redacted]; any other body field, a password included, is masked entirely. Applied to the logger and to whatApiConfig.observerreceives; only those copies are masked.redact: falseturns it off. Built as a wrapper around the logging interceptor, so it does not depend on PrettyDioLogger's output format. - Helpers for chained flows:
ApiException,orThrow()andguardApi.orThrow()on any request'sFuture<Either<Failure, T>>(or an awaitedEither) returns the value or throws anApiExceptionwrapping theFailure(withstatusCode,data,messageanderrorType).guardApi(() async { ... })turns such a flow back intoEither<Failure, T>: anApiExceptionbecomes itsFailure, a thrownFailureorDioExceptionbecomes the correspondingFailure, and anything else becomesErrorSource.defaultError, reported to the optionalonUnexpected. The failuresguardApibuilds itself go throughApiConfig.mapFailure, of the default client or the one named byclient:. jwtExpired(token, {skew})andjwtExpiryCheck(getToken, {skew}). Reads a JWT'sexp(base64url, padding restored) and reports whether it has passed, or will withinskew(default 30 seconds). A malformed token counts as expired; one withoutexpnever expires.jwtExpiryCheckplugs straight intoAuthConfig.isTokenExpired, and treats a missing token as not expired. The signature is not verified — this decides when to refresh, not whether to trust.- Named clients.
ApiServices.init(config, name: 'partner')builds a second, independent client, reached withApiServices.named('partner')— for an app talking to two backends with different hosts, auth, certificates, proxies, timeouts or retries, which used to need a hand-built second Dio. Each client has its own configuration, auth, retry policy, concurrency cap, connectivity cache, de-duplication and cancellation. Also new:ApiServices.defaultClient,configOf(name),isInitialized([name]),reset(name: ...)(no name still resets everything),configureLoader(name: ...)for a client-specific indicator (without one, clients share the global indicator and its count), andFakeApiServices(client: ...). The default client,init(config)andinstance()are unchanged.
Fixed #
- Joining
baseUrland an endpoint could drop or double a slash. Dio concatenates the two, sohttps://api.example.com/v1+userswent to/v1users, and a trailing-slash base plus an endpoint whose query held a URL (/cb?next=https://...) kept its//. The base is now trimmed of trailing slashes and a relative endpoint always gains a leading one; an endpoint written with its leading slash reaches interceptors,skipRefreshand the observer unchanged.
Changed #
ApiServices.reset()takes an optionalname, and without one now resets every client — for an app with only the default client, exactly what it did before.tearDown(ApiServices.reset)still works.- The Dio client's
baseUrlis stored without trailing slashes, and a relative endpoint missing its leading slash gains one (see Fixed). Only code readingdio.options.baseUrldirectly would notice. - The observer receives masked copies of requests, responses and failures (see log redaction, above). An observer that forwarded tokens or passwords somewhere now forwards
eyJh…[redacted]; setApiLogOptions(redact: false)to restore the raw values. What callers receive is unchanged.
4.0.0 #
The first release on pub.dev since 2.0.0: 3.0.0 and 3.1.0 were never published. Upgrading from 2.0.0 means reading the 3.0.0, 3.1.0 and 4.0.0 sections below, and following the 3.0.0 and 4.0.0 steps in MIGRATION.md.
See MIGRATION.md for upgrade steps.
⚠️ Breaking changes #
- Requires Dart 3.8 / Flutter 3.32. The constraint used to claim Dart 3.3.1, but the package's own tooling needed 3.8, so nothing older was ever built or tested.
- Response caching is removed, along with the
api_cache_managerdependency (andsqflitebeneath it). Every request goes to the network. Removed:CachePolicy,ApiCacheHelper, theAPICacheDBModelre-export, theCachedResponseextension (response.isFromCache), thecachePolicyandcacheMaxAgeparameters onget/getAs(and onFakeApiServices), and theApiConfigfieldscacheEnabled,defaultCachePolicy,cacheMaxEntriesandcacheMaxBytes. 504 Gateway Timeouthas its own error:ErrorSource.gatewayTimeout/ResponseCode.gatewayTimeout. It used to fall through todefaultErrorwith "An unexpected error occurred", unlike its neighbours502and503. Exhaustive switches need a case for it.isSuccessis no longer applied tohead(). AHEADresponse has no body, so a predicate reading it — the commonr.data['success'] == true— threw on every call, and a throw counts as a rejection.download()already skipped it.ErrorSource.cacheErrorandResponseCode.cacheErrorare removed. Exhaustive switches naming them stop compiling. The code-5is retired, not reused:mapStatusCodeToEnum(-5)now returnsdefaultError.- The unexported
src/utils/response_messages.dartshim is deleted. AuthConfig.onTokenRefreshis no longer required, and its field is nullable, sincerefreshSession(below) is the alternative to it. Passing it works exactly as before; only code that readsconfig.auth!.onTokenRefreshneeds a null check.
Added #
AuthConfig.skipRefresh. Requests whose401must not trigger a refresh. A wrong password on the login screen used to start a refresh with nothing to refresh, which failed and firedonRefreshFailed— logging the user "out" of the login screen. Logout belongs here too. Matched requests still carry the token.AuthConfig.refreshSessionandRefreshOutcome. An alternative toonTokenRefreshthat says why a refresh failed.sessionExpiredfiresonRefreshFailed;failed— offline, a timeout, a5xx— does not, so losing signal mid-refresh no longer signs the user out. A throw counts asfailed.AuthConfig.isTokenExpired. Refreshes before sending a request whose token has run out, instead of spending a round trip on a401. Concurrent requests share one refresh. When the refresh ends the session the request is not sent and fails as a401; when it merely fails, the request goes out with the token it has, and its401does not refresh a second time.ApiConfig.mapFailure. Rewrites anyFailurebefore the caller sees it — HTTP errors, timeouts, offline, cancellation, parse errors and rejected bodies — so app-specific messages and failure kinds live in one place.FakeApiServicesapplies it too.Failure.errorCode. The server's own error code, read fromcodeorerrorCodeat the top level or inside anerrorobject.
Fixed #
download()sentAccept: application/json, which servers that honour it — static file handlers in particular — answer with406. Downloads, and requests forResponseType.bytesorstream, now sendAccept: */*unless the caller passes its own headers.- ASP.NET validation errors showed the generic message. Its automatic
400body,{"title": ..., "errors": {...}}, has neithermessagenordetail. When none of the usual keys has anything, the field messages undererrorsare now used, thentitle. - A refresh token that had expired froze the app for
refreshTimeout(30s) before signing out. WhenonTokenRefreshrefreshed through the same client and the refresh endpoint answered401, that401waited on the very refresh it belonged to until the timeout, loader showing. It now fails at once andonRefreshFailedfires immediately. - A
GETmade insideonTokenRefreshcould deadlock undermaxConcurrentRequests. De-duplication collapsed it onto an identical request queued behind the one awaiting the refresh, skipping the refresh's bypass of the concurrency cap. Requests made during a refresh are no longer de-duplicated. ApiServices.reset()left a showing loader on screen for good. The in-flight request's hide was correctly ignored as stale, but nothing else closed the dialog.reset()now callsonHidewhen a loader is showing.- Exponential backoff broke past 63 retries.
pow(2, n)on integers wrapped negative, so the delay slipped under themaxDelayclamp and the jitter threwRangeError— replacing the real error withunknown. Backoff is now computed in doubles. - A retry could replace a real
429/503with anunknownerror, losing its status and body: aRetry-Afterheader sent twice made Dio'sHeaders.valuethrow, as did a throwingRetryPolicy.retryIf. A repeated header now uses its first value, and a throwingretryIfmeans "don't retry". Retry-After: -5retried immediately. A negative (invalid) value now falls back to the computed backoff, and only plain digits are read as delta-seconds.- FastAPI/Pydantic
422messages were lost. A{"detail": [{"msg": "field required", ...}]}body fell back to the generic text. List entries that are objects are now read like any other body, andmsgis recognised. - A JSON error body received as a string —
responseType: plain, or JSON served astext/plain— became the raw{"message": ...}text inFailure.message. It is now decoded and read. Base64LogTrimmercut long url paths, hex digests and slash-heavy file paths out of the log, since/is in the base64 alphabet. A run must now also mix upper and lower case and be no more than one-tenth/.- A
401from before the previous refresh, arriving during the next one, failed for good. It replayed at once with the token that refresh was replacing, got a second401, and — replayed only once — surfaced it. It now waits for the running refresh. - A refresh landing while a request read its token could trigger a redundant refresh. The request recorded the post-refresh generation alongside the pre-refresh token, so its
401looked current. The generation is now read before the token. - A
Streamrequest body broke both retry paths. A429/503retry or a401replay re-read the spent stream and failed with anunknownerror wrappingStateError, losing the real status. Stream bodies are no longer replayed; the original error surfaces. Pass bytes orFormDataif the upload must be retryable. FakeApiServicesdiverged from the real client: itsdownloadappliedApiConfig.isSuccess, which production never does; it ignored an already-cancelledCancelToken, which production fails withErrorSource.cancel; and it never reported toApiConfig.observer. It now callsonRequest/onResponse/onFailureas production does, and its failures carry theRequestOptionsthat produced them.
Changed #
Failure.toString()includesstatusCode, so an unmapped status no longer logs only ascode: -7.- The pubspec now declares
repositoryandissue_tracker(the 3.0.0 entry claimed this, but they were never added).
Unchanged #
- In-flight de-duplication of identical
GET,HEADandOPTIONSrequests works as before.
3.1.0 #
Not published to pub.dev; included in 4.0.0.
Fixed #
-
maxConcurrentRequestsdeadlocked a token refresh made through the client. A request that401'd held its slot while awaiting the refresh, so a refresh request sent throughApiServices— the shape the README shows — queued behind the very requests waiting on it. A cap of1hung forever; a cap of n with n concurrent401s stalled untilrefreshTimeoutand then failed them all. Requests made from insideonTokenRefreshnow bypass the cap. -
cancelRequest()andreset()missed requests still in the connectivity probe. The token was registered only once the probe had passed, so a request cancelled — or orphaned by a logout'sreset()— during the probe went out anyway, and could write the previous user's response into the cache. Tokens are now registered for the request's whole life, and a client discarded byreset()sends nothing further. -
A
CancelTokenshared by several requests escapedcancelRequest(). The first request to finish unregistered it for all the others. -
A
GETbody was not part of its cache key. Two searches differing only in their body shared an entry, so the second was answered with the first's results. AGETwith a body that cannot be encoded is no longer cached. -
A plain-text caller could be served a JSON caller's cached
Mapfor the same url, and vice versa.responseType: plainresponses are cached under their own key. -
Duplicate cache rows froze an entry for good. Once a key had two rows — from a second isolate, or left over from 1.x — every write inserted another and every read returned the oldest, so the cache served its first-ever response forever. Each write now clears the key first, which heals it.
-
An expired entry's cleanup could delete a fresh write for the same key that landed in between. The cleanup now runs in that key's write queue, and only removes the row it judged stale.
-
A late
401could still trigger a second refresh when the token string was unchanged across the refresh, or read stale while it landed. Each request now records the refresh generation it was sent under, which is checked synchronously. -
A broken loader callback broke the request. A throwing
onShow—navigatorKey.currentContext!before the navigator mounts, say — escaped as an exception and left the loader count stuck so it never showed again; a throwingonHidereplaced the request's result. Both are now contained, like observer callbacks. -
A throwing
onRefreshFailedreplaced the401. Code checking forErrorSource.unauthorizedsaw a generic error instead. -
A huge
Retry-Afterretried immediately. Delta-seconds large enough to overflowDurationwrapped negative and slipped under themaxDelayclamp. -
A device clock set backwards stretched the connectivity cache until the clock caught up, reporting "connected" from a stale probe.
-
maxConcurrentRequests: 0queued every request forever. It is now rejected by an assert, and treated as1in release builds. -
upload()sent only the last of several files sharing a field. TheFormDatawas built from a map literal, soUploadFiles with the samefield— a gallery'simages, say — were duplicate keys and all but the last were silently dropped. Each file is now appended as its own entry. -
A throwing
ApiConfig.isSuccessescaped as an exception. A predicate written for an envelope body, such asr.data['success'] == true, threw on a204'snullbody, breaking the guarantee that no exception crosses the API boundary. A throw now counts as a rejection (it fails closed, likeAuthConfig.sendTokenTo) and routes throughonRejectedas usual. -
A late
401started a second, redundant token refresh. A request sent with the old token whose401arrived only after another request's refresh had finished saw no refresh in progress and refreshed again — against a backend that rotates refresh tokens, a refresh that can fail and sign the user out. A401for a token that has since been replaced now replays with the current token instead. -
ApiServices.reset()left the discarded client's requests running. On logout, one that finished afterwards could write the previous user's response back into a cache that had just been cleared.reset()now cancels them; they complete withErrorSource.cancel. -
De-duplication could hand a caller another caller's response. The in-flight key ignored headers and
responseType, so aGETsent withAccept-Language: urcould receive the response to a concurrent English one, and aresponseType: bytescaller could receive a decoded map. Bodies were keyed bytoString(), so two different model objects without their owntoString— bothInstance of 'Query'— were treated as one request. A follower'sonSendProgress/onReceiveProgressnever fired, since only the originator's callbacks reach Dio. Headers (case-insensitively) andresponseTypeare now part of the key, bodies are compared as JSON (an unencodable body is never collapsed), and a call with a progress callback goes out alone. -
cancelRequest()did not reach a request queued behindmaxConcurrentRequests. The queue sits outside Dio, so Dio's cancellation never saw it: a cancelled request waited for a free slot before failing, holding the loader the whole time — behind a long upload, the whole upload. It now fails withErrorSource.cancelimmediately, never reaches the network, and gives its place in the queue to the next request. -
ApiServices.reset()during a request broke the loader permanently. The in-flight request's release took the zeroed count to-1, so the next request's increment landed on0andonShownever fired again. Releases from before areset()are now ignored. -
Binary responses were cached as JSON. A
responseType: bytesbody was stored as a JSON list and served back asList<dynamic>instead ofUint8List; and since the cache key has no response type, abytescaller could be served a map cached by a JSON caller of the same url.bytesandstreamrequests now bypass the cache. -
cacheMaxBytescould evict live entries for space that was already free. Entries deleted byclearCachebefore the eviction index was loaded, or expired bycacheMaxAge, stayed in the index and kept counting against the cap. Sizes were also measured in UTF-16 code units rather than bytes, undercounting non-ASCII bodies up to threefold. -
An HTML error page became
Failure.message. A gateway's502/504page (nginx, Cloudflare, a load balancer) was surfaced verbatim, markup and all. HTML bodies now fall back to the generic message for the status. A boolean such as{"error": true}is no longer reported as the message"true", and an emptymessageno longer hides a laterdetailorerror. -
A failed token replay reported the wrong error. When the replay after a successful refresh threw anything other than a
DioException—getToken()failing, say — it fell into the refresh's owncatch, which completed the refresh completer a second time. The request failed withBad state: Future already completedin place of the real cause. The replay now handles its own errors and the original is preserved.
Changed (test double) #
FakeApiServicesnow builds failures the way the real client does.stubFailuremaps the status (401→ErrorSource.unauthorized) and reads the body's message, where it always producedbadRequestwith the generic text.stubJsonwith a non-2xxstatus is a failure, as Dio makes it.ApiConfig.isSuccessapplies to stubbed responses. A consumer test that asserted the old, unrealistic values will need updating — it was passing against behaviour production does not have.
3.0.0 #
Not published to pub.dev; included in 4.0.0.
See MIGRATION.md for upgrade steps. Most apps need only the first item.
⚠️ Breaking changes #
- Requires
equatable3.FailureextendsEquatable, so this package and your app must agree on its major version. If your app pinsequatable: ^2.x, raise it to^3.0.0. - The deprecated 1.x configuration methods are removed.
ApiServices.configure(),setConnectivityCheck()andsetLogging()were deprecated in 2.0.0 and scheduled for removal in this release. UseApiServices.init(ApiConfig(...)); the mapping is inMIGRATION.md. HttpMethodgainedheadandoptions. Aswitchthat covers everyHttpMethodvalue no longer compiles until you add the two cases or a wildcard.ApiServicesgainedhead()andoptions(). Code that implementsApiServicesdirectly, instead of usingFakeApiServices, must add them.
Changed #
- Minimum
diois now5.11.0, and minimuminternet_connection_checker_plusis now3.1.2. - Added
repositoryandissue_trackerto the pubspec.
Fixed #
- The auth token was sent to every host the client talked to.
TokenRefreshInterceptorattached it with no host check, whileApiConfig.baseUrldocuments absolute endpoints as a supported way to reach a CDN or third party from the same client — so a session token travelled to whoever the caller named. It also broke the most common reason to use an absolute endpoint: S3 rejects a presigned URL request that also carries anAuthorizationheader. The token now goes only to thebaseUrlhost by default, overridable withAuthConfig.sendTokenTo. A401from an unscoped host no longer triggers a refresh either, so a third party's401cannot cascade intoonRefreshFailedand sign the user out. - A
401arriving during a token replay triggered a second, redundant refresh.TokenRefreshInterceptorreturned the replayed request without awaiting it, so thefinallythat clears_isRefreshingran while the replay was still in flight. Any request that401'd in that window saw no refresh in progress and started its own — the stampede the interceptor exists to prevent, and a real hazard against a backend that rotates refresh tokens. The replay is now awaited. - A project-wide
defaultCachePolicycached writes.CachePolicyis documented as aget/getAs-only contract, and only those methods expose the argument — butApiConfig.defaultCachePolicyapplies to every request that does not name one, which is everypost,put,patchanddeletethere is. Setting it project-wide meant a repeatedPOST /orderswas answered from the cache and never reached the server. Cache keys carry no method or body either, so aPOST,PUT,PATCHandDELETEon one path all shared a single entry, and aPOSTresponse could be served to a laterGET. Caching is now restricted toGETwhere the policy is resolved, rather than relying on the method signatures to enforce it. ApiConfig.defaultHeaderswas documented backwards. The dartdoc claimed a request's ownheadersreplace the defaults; they are merged over them, which is what the README always said and what the code always did.
Added #
ApiConfig.interceptors. Your own Dio interceptors, for anything that needs to modify a request rather than just watch it — correlation ids, tenant headers, request signing, a fixture router for local development. Inserted after auth (so a signer sees theAuthorizationheader) and before retry and the logger (so replays re-run them and the log shows their work).Interceptor,InterceptorsWrapper,QueuedInterceptor, the three handler types,DioException,DioExceptionTypeandHttpClientAdapterare now exported, so writing one needs no directdiodependency —HttpClientAdapterin particular was already referenced by public config but was not on the surface.ApiConfig.maxConcurrentRequests. Caps requests in flight, queueing the rest in the order they were made. Firing twenty requests at once saturates a mobile connection pool and reliably trips server-side rate limiting thatretrythen has to clean up. The cap governs real network calls — cache hits and de-duplicated callers do not consume a slot — and a queued request stays cancellable. Unset by default, which is unlimited.responseTypeon every request method. Fetch bytes or plain text instead of decoded JSON — an image into memory, or a CSV export — without dropping to raw Dio.ResponseTypeis re-exported.head()andoptions().RetryPolicy.idempotentMethodsalready listedHEADandOPTIONS, but neither was reachable through the public API.HttpMethodgained matching variants, andHttpMethodExtension(soHttpMethod.get.valueworks) is now exported.- Cancellation by tag. Requests accept a
tag, andcancelRequest(tag: 'feed')cancels only those — previously it was all-or-nothing, so one screen tearing down aborted requests belonging to screens still on the stack. Omitting the tag still cancels everything. A tagged request opts out of de-duplication, for the same reason a caller-suppliedCancelTokendoes. ApiConfig.onRejected. Builds theFailurefor a2xxthatisSuccessrejected, so an API reporting its own error codes in the body no longer collapses to a genericbadRequest. Returningnullfalls back to the previous behaviour.ApiConfig.connectivityProbe. Replaces the default third-party ping with your own check — a health endpoint, typically. The default is blocked on some corporate networks and says nothing about whether your API is reachable, and until now the only alternative was disabling the check wholesale.ApiConfig.cacheMaxEntriesandcacheMaxBytes. The cache was unbounded: every distinct url and query combination added an entry nothing removed, andcacheMaxAgeonly discards a stale entry when something reads it. Past either cap the oldest entries are now evicted. Both default tonull, leaving the cache unbounded exactly as before.
2.0.0 #
Everything from 1.x keeps working — the old entrypoints are deprecated, not removed. See MIGRATION.md for the three things that can actually break you.
⚠️ Behaviour changes to know about before upgrading #
- Requests now time out. 1.x set no timeout at any layer, so a request to an unreachable-but-not-refusing host hung until the OS gave up. The defaults are 30s each for connect/receive/send. If you have an endpoint that legitimately takes longer — a slow export or report — raise
receiveTimeoutfor that call or globally, rather than removing the bound. ErrorSourceandResponseCodegained aparseErrorvariant. If youswitchexhaustively over either enum, that switch no longer compiles until you add a case. This is the only source-breaking change and the reason this is a major release.Failureequality now includesdataandstatusCode. Two failures that differ only in response body are no longer equal.
Fixed #
ApiCacheHelper.getCacheDatathrew on a cache miss. The underlyingAPICacheManager.getCacheDatacalls.firston an empty query result, so asking for a URL that was never cached raisedStateErrordespite the nullable return type promising otherwise. It now returnsnull.- Concurrent writes to one cache key could poison it permanently.
APICacheManager.addCacheDatachecksisAPICacheKeyExistand then inserts or updates, with no transaction around the pair, so two overlapping writes both insert. The duplicate rows are not self-correcting:isAPICacheKeyExistanswersrows.length == 1, so it then reports the key as missing forever while every further write appends another row. Request de-duplication makes overlapping same-key writes routine rather than rare, sosetCacheDatanow serialises writes per key. - Uploads threw instead of retrying. A
FormDatais a stream Dio reads once —finalize()throwsStateErroron a second read. Both replay paths hit it: a429/503retry (those bypass the idempotency check, so an upload is retried) and a401token refresh, which is a likely outcome for an upload long enough to outlive its token. The body is now rebuilt withFormData.clone()before either replay. - A JSON
content-typein caller-supplied headers broke multipart uploads. It was only stripped from the package's default headers, so an upload that also needed, say, anX-Tenant-Idheader silently sentapplication/jsonand lost the multipart boundary. - A connectivity probe that threw synchronously disabled the check permanently. An
asyncbody runs synchronously to its firstawait, so such a probe completed — and cleared the in-flight slot — before that slot was assigned, stranding a completed future that reported offline for the rest of the session. - Cached entries with query parameters collided. The cache key was the raw url, so
/userswithparams: {'page': 1}andpage: 2shared one entry and the second overwrote the first. Query parameters are now part of the key, sorted so argument order does not matter. - The connectivity probe ran before every single request — a real network round-trip that roughly doubled the latency of a fast API call. A positive result is now reused for
connectivityCacheTtl(default 5s). Negative results are deliberately never cached, since that is exactly when the user is retrying. Failurediscarded the response body, making422field errors unreachable.- Interceptor order was assembled across two call sites and did not match the documented order. It is now fixed in one place, with auth before retry so a retried request carries a valid token.
DioExceptionType.badCertificatemapped to the generic "unexpected error" instead ofconnectionFailure.
Added #
ApiConfig+ApiServices.init(...)— one object for every setting, replacingconfigure()and the loose static setters. AddsbaseUrl(so call sites pass/users, not the full URL),connectTimeout/receiveTimeout/sendTimeout, anddefaultHeaders.- Typed responses —
getAs<T>,postAs<T>,putAs<T>,patchAs<T>,deleteAs<T>take aparserand returnEither<Failure, T>. A throwing parser becomes aFailurewithErrorSource.parseErrorcarrying the raw body; no exception escapes.listParser(User.fromJson)handles list endpoints, with an optionalkeyfor{"data": [...]}wrappers. - Response caching —
cachePolicyandcacheMaxAgeonget/getAs, withCachePolicy.cacheFirst,networkFirst,cacheOnly, and the defaultnetworkOnly(unchanged behaviour).response.isFromCachetells you which you got.ApiCacheHelperwas already in the package but nothing called it. - Project-level cache control —
ApiConfig.cacheEnabled: falseforbids caching outright, overriding anycachePolicya call site passes and never opening the database;ApiConfig.defaultCachePolicysets the policy for calls that don't name one. Not every app should cache, and "just don't pass a policy" relies on every call site getting it right. ApiLogOptions.trimBase64— collapses base64 blobs in log output. An API returning photographs or fingerprints inline turns a single response into thousands of console lines, because the logger wraps every value atmaxWidthand has no notion of a field worth hiding. With this on, a blob prints as a recognisable head plus a count of what was elided, and everything else passes through byte for byte. Off by default.Base64LogTrimmeris exported for tuningminRunLength/keptCharsor placing the trimmer in front of your own sink.- In-flight de-duplication — two identical GETs at the same time share one network call. Skipped automatically when you pass your own
CancelToken, since cancelling one caller must not cancel the other; opt out withdedupe: false. RetryPolicy— configurablemaxRetries,baseDelay,maxDelay,retryableStatusCodes, and aretryIfpredicate. Retries now cover status codes as well as transport errors:429and503for any method (the server told us it did not process the request),408/500/502/504for idempotent methods only.Retry-Afteris honoured in both its delta-seconds and HTTP-date forms. Backoff is exponential with full jitter, replacing the lockstep linear interval that made concurrent failures retry in unison.ApiConfig.isSuccess— treat a200carrying{"success": false}as a failure, with the message pulled from the body the same way a real error response would be.ApiObserver— one hook for every request, response, and failure, for Sentry/Crashlytics/analytics. Fires exactly once per call, including for failures Dio never produces an exception for (offline short-circuits, parse errors,isSuccessrejections). A throwing observer can never break a request.ApiConfig.httpClientAdapter— supply your own adapter for certificate pinning or to route through Charles/Proxyman. Deliberately consumer-supplied so the package stays usable on web.upload()— multipart uploads with progress, takingUploadFile.fromPath(mobile/desktop) orUploadFile.fromBytes(web, where a picked file has no path). The multipart body is rebuilt before any replay — a429/503retry or a401token refresh — because aFormDatais a stream that Dio reads once and refuses to read again. A JSONcontent-typeis stripped for multipart bodies, including one you pass yourself.ApiServices.reset()— clears the singleton, config, and loader callbacks. FixessetLoggingbeing silently a no-op after the firstinstance()call, and gives tests a clean slate.package:baaba_api_handler/testing.dart— shipsFakeApiServices, an in-memory double with stubbing and call recording, so consumers can test repositories without mocking Dio. An unstubbed endpoint throws aStateErrornaming it rather than quietly returning null.Failure.data,Failure.statusCode,Failure.validationErrors,Failure.requestOptions— the raw body, the literal HTTP status (codecollapses anything unrecognised todefaultError), per-field errors parsed from a{"errors": {...}}body, and the request that failed.requestOptionsis excluded from equality: it is context about where a failure came from, not part of what the failure is.package:baaba_api_handler/baaba_api_handler.dartas the conventional entrypoint. The oldts_api_handler.dartimport still works.
1.4.0 #
- Added
ApiLogOptions— the consuming app now controls what the console logger prints:enabled,request,requestHeader,requestBody,responseHeader,responseBody,error,maxWidth,compact, andlogPrint. Previously the logger was hardcoded torequestBody: truewith no way to change it. Includes anApiLogOptions.disabled()constructor andcopyWith. - Added
loggingparameter toApiServices.configure(), defaulting toconst ApiLogOptions()— same output as before, so existing callers see no change. - Added
ApiServices.setLogging(ApiLogOptions)— same control for apps that don't use token auth. Must be called before the firstApiServices.instance(), since the Dio client and its logger are built once and cached. - Release builds are unaffected: the logger is still never attached when
kReleaseModeis true.
1.3.1 #
- Added support for the
detailkey in API error responses (RFC 7807), falling back to it ifmessageis missing but prioritizing it overerror.
1.3.0 #
- Added
ApiServices.download()— streams a file response directly to disk (savePath) instead of loading it into memory, withonReceiveProgress,cancelToken, anddeleteOnErrorsupport. Goes through the same connectivity check and loader plumbing as the other HTTP methods. - Added
refreshTimeoutparameter toApiServices.configure()(default 30 seconds). Bounds how long a request that 401s while another refresh is already in flight will wait for that refresh before giving up and failing with the original error. TokenRefreshInterceptor: requests that 401 while a refresh is already in progress now wait for that refresh to finish and retry with the fresh token, instead of failing immediately. Previously only the first request in a concurrent-401 burst would succeed; the rest errored out just for losing the race.NetworkRetryInterceptornow only auto-retries idempotent methods (GET,HEAD,OPTIONS,PUT,DELETE).POST/PATCHare no longer retried on transient timeouts/connection errors, since the server may have already processed the request and a blind retry could duplicate the side effect.- Added
maxAgeparameter toApiCacheHelper.getCacheData()— if the cached entry is older thanmaxAge, it's treated as a miss (the stale entry is cleared andnullreturned) instead of returning stale data. Omit it to keep the previous behaviour of returning cached data regardless of age. - Bumped
dioto^5.10.0,pretty_dio_loggerto^1.4.0,internet_connection_checker_plusto^3.1.1,fpdartto^1.2.0,equatableto^2.1.0, andsqflite_common_ffi(dev) to^2.4.0+3.
1.2.0 #
- Added
ApiServices.configureLoader({onShow, onHide})— a global, framework-agnostic loading indicator shown automatically around every request (success, failure, and thrown exceptions all covered), so callers no longer need a per-screenisLoadingflag.onShow/onHideare plain callbacks (e.g.Get.dialog/Get.backfor GetX, orshowDialog/Navigator.popwith a global key) — the package has no UI dependency. - Added
showLoaderparameter (defaulttrue) toget/post/put/patch/deleteto opt a specific request out of the loader. - Concurrent requests share one indicator via reference counting:
onShowfires only for the first in-flight request,onHideonly once every in-flight request has finished.
1.1.0 #
- Breaking:
ErrorSourceenum variants renamed fromsnake_casetocamelCase(e.g.no_content→noContent,bad_request→badRequest). Update anyswitchor direct references in your code. - Added
bypassConnectivityCheckparameter toApiServices.configure()for staging/internal environments where connectivity probes fail due to proxies or firewalls. - Added
ApiServices.setConnectivityCheck({bool enabled})— controls the connectivity check independently of token auth configuration. cancelRequest()now cancels all in-flight requests (previously only the most recent). All activeCancelTokens are tracked in aSetand cancelled together.- Extended
ResponseCodeandErrorSourcewith six new HTTP status codes:created(201),requestTimeout(408),conflict(409),unprocessableEntity(422),tooManyRequests(429),badGateway(502). - Fixed
ResponseCode.noContentraw value from 201 to 204. ResponseCoderefactored to use inline integer values (ResponseCode.success(200)style) — no longer requires an extension for.value.ResponseStringsrewritten with cleaner, user-facing error messages.ErrorHandlerno longer implementsException.
1.0.7 #
- Added
TokenRefreshInterceptorfor automatic token refresh on 401 responses. - Added
NetworkRetryInterceptorfor automatic retry on transient network failures. - Added
ApiServices.configure()static method for setting up token-based authentication. - Added
headerBuilderparameter toApiServices.configure()for customising auth headers per request. - Added
onSendProgress,onReceiveProgress, andCancelTokenparameters to all request methods. - Re-exported
ResponseandCancelTokenfrom Dio, andAPICacheDBModelfrom api_cache_manager — no separate imports needed.
1.0.6 #
- Added
SERVICE_NOT_AVAILABLE(503) toResponseCodeand error handling. - Improved error message extraction from API response body (
messageanderrorkeys).
1.0.5 #
- Updated readme documentation and bumped version.
1.0.4 #
- Added license information.
1.0.3 #
- Updated package structure and internal functionality.
1.0.2 #
- Fixed multipart request method naming.
- Fixed incorrect MIME types in multipart requests.
1.0.1 #
- Added multipart request support.
- Updated dependencies.
1.0.0 #
- Initial release.
- HTTP methods: GET, POST, PUT, PATCH, DELETE.
- API response caching via
ApiCacheHelper. - Network connectivity checks before each request.
- Structured error handling with
Failure,ErrorSource, andResponseCode.