flutter_api_client library

Flutter API Client — a production-ready, type-safe HTTP client for Flutter/Dart.

Key Features

Core HTTP Client

  • Type-safe generic methods: get<T>, post<T>, put<T>, patch<T>, delete<T>, and query<T> (the safe-with-body HTTP QUERY method)
  • Sealed ApiResult<T> with exhaustive Success/Failure pattern matching
  • Custom decoders to transform JSON directly to your model types
  • Multiple response modes: JSON, bytes, and plain text (real streaming is available separately via ApiClient.stream())
  • Multipart file uploads with progress tracking
  • Automatic query parameter encoding

Authentication & Security

  • Pluggable TokenStorage interface for secure token persistence
  • Concurrent-safe 401 token refresh with request queue
  • Automatic Bearer token injection
  • Header redaction in logs for sensitive data protection

Resilience & Performance

Spec-Driven Development

GraphQL Support

  • GraphQLClient: Query, mutation, and APQ support
  • Typed error handling with GraphQLError
  • Variable validation and SDL generation from specs

Testing

  • MockAdapter: Route-based mocking with request capture
  • No external mock dependencies

Quick Start

final client = ApiClient(
  ApiClientConfig(
    baseUrl: 'https://api.example.com',
    interceptors: [
      RetryInterceptor(policy: RetryPolicy()),
      CacheInterceptor(store: MemoryCacheStore()),
      PrettyLogger(),
    ],
  ),
);

final result = await client.get<User>('users/me', decoder: (json) => User.fromJson(json as Map<String, dynamic>));
result.when(
  success: (user) => print('Hello ${user.name}'),
  failure: (error) => print('Error: ${error.message}'),
);

See CHANGELOG.md for what changed in each release.

Classes

AdapterRequest
Low-level request passed to an HttpAdapter.
AdapterResponse
Low-level response returned by an HttpAdapter.
ApiClient
HTTP API client with pluggable transport, interceptors, retries, caching, dedup, refresh-queue auth, and spec-driven mocks.
ApiClientConfig
Configuration for ApiClient.
ApiClientInterface
Public API of an HTTP client.
ApiResult<T>
Sealed result type returned by all API calls.
ApiSpec
A spec is the source of truth: it drives mocks, OpenAPI, and docs.
ApiSpecEntry
Marks a top-level ApiSpec variable for discovery by dart run flutter_api_client:gen.
AuthInterceptor
Attaches the auth token, retries on 401 with concurrent-safe refresh.
BackendGuideGenerator
Generates a backend-implementation guide in Markdown. Designed to be handed to a backend engineer so they can build the API surface the client expects.
CachedTokenStorage
Wraps any TokenStorage with an in-memory cache so reads are sync-fast and writes return immediately (persistence happens in the background).
CacheEntry
A cached HTTP response entry.
CacheInterceptor
Caches GET responses according to a CachePolicy.
CachePolicy
How the CacheInterceptor should treat a given request.
CachePolicyInterface
Implemented by CachePolicy in interceptors/cache/cache_policy.dart. See RetryPolicyInterface.
CacheStore
Pluggable cache backend. Implement this to persist cached responses somewhere other than memory.
CancelToken
Cancels one or more in-flight requests from the package API perspective.
Charset
Pluggable body-charset codec.
CircuitBreakerInterceptor
Fails fast when an origin looks down, instead of letting every request wait out its full timeout.
ClientCustomization
Immutable bundle of the client's fine-grained customization knobs.
CurlLogger
Logs each request as a ready-to-paste cURL command.
DedupInterceptor
Coalesces identical in-flight GET requests so the network is only hit once. Other matching callers receive the same response.
DefaultHttpAdapter
Default adapter built on package:http.
DefaultResponseJsonCodec
Default ResponseJsonCodec delegating to dart:convert's jsonDecode.
EndpointGroup
Fluent helper passed to ApiSpec.group.
EndpointSpec
A single endpoint in the spec.
EnumerableCacheStore
A CacheStore that can enumerate the keys it holds.
Failure<T>
Failed API result carrying a typed ApiException.
FormData
Lightweight helper for building multipart form data.
GraphQLClient
GraphQL client built on top of ApiClient.
GraphQLError
A single error returned in the errors array of a GraphQL response.
GraphQLErrorExample
Example of a GraphQL error to include in docs / mocks.
GraphQLOperation
A single GraphQL operation declaration in an ApiSpec.
GraphQLResponse<T>
Result of a GraphQL operation. Carries data, any errors, and the underlying HTTP status code.
GraphQLSection
GraphQL section of an ApiSpec. Contains the HTTP path the gateway is served at plus a list of GraphQLOperations.
HiveCacheStore
Persistent Hive-backed cache store.
HiveOfflineQueueStore
Persistent Hive-backed queue store.
HttpAdapter
Pluggable transport. Swap out DefaultHttpAdapter for cupertino_http, cronet_http, or a MockAdapter in tests.
HttpStreamResponse
A streaming HTTP response whose body is delivered incrementally as bytes.
InMemoryOfflineQueueStore
Default in-memory queue store (volatile). Replace with a persistent implementation for real offline support.
InterceptedRequest
Fully-resolved request flowing through the interceptor chain.
Interceptor
Base interceptor. Override the hooks you need; each defaults to a no-op that simply lets the chain continue.
InterceptorChain
Coordinates the ordered run of Interceptors around the transport call.
InterceptorResult
Result returned from each step of the chain.
JsonRequestBodySerializer
Default RequestBodySerializer: JSON via dart:convert, bytes via a Charset (UTF-8 by default).
MarkdownDocGenerator
Generates a human-readable Markdown API reference from an ApiSpec.
MemoryCacheStore
Bounded in-memory LRU cache store.
MemoryTokenStorage
In-memory TokenStorage for tests or simple use cases.
MockAdapter
HTTP adapter that returns canned responses, perfect for tests.
MockRoute
Route matcher used by MockAdapter.
OfflineAutoReplay
Replays the offline queue automatically when connectivity returns.
OfflineMutations
Optimistic offline mutations with pluggable local-data callbacks.
OfflineQueueInterceptor
Detects network errors on mutating requests and stores them for replay.
OfflineQueueReplayer
Re-issues the pending mutations in an OfflineQueueStore through a live ApiClient.
OfflineQueueStore
Persists pending mutations while offline. Pluggable so users wire their own storage backend.
OfflineReplayReport
Outcome of an OfflineQueueReplayer.replay pass.
OfflineSyncManager
Drives OfflineQueueReplayer automatically from a connectivity signal.
OpenApiGenerator
Emits an OpenAPI 3.1 document (JSON or YAML) derived from an ApiSpec.
PeekableOfflineQueueStore
An OfflineQueueStore that can also be read non-destructively.
PrettyLogger
Pretty, line-broken request/response logger with optional ANSI colors and header redaction.
ProceedResult
Continue the chain with request (possibly mutated).
QueryEncoder
Configurable serializer for URL query strings.
QueuedRequest
A request captured while offline, pending replay.
RejectResult
Short-circuit the chain and fail with error.
RequestBodySerializer
Turns a request payload into the encoded body handed to the transport.
RequestExample
Example request payload for an endpoint.
RequestOptions
Per-request options.
ResolveResult
Short-circuit the chain and return response without further transport.
ResponseExample
Example response for an endpoint.
ResponseHandler
Default response handler that extracts a human-readable message from a JSON error envelope and detects HTML / plain-text bodies.
ResponseHandlerInterface
Pluggable response error message extractor.
ResponseJsonCodec
Parses a decoded response String into a JSON value.
RetryInterceptor
Retries failed requests according to a RetryPolicy.
RetryPolicy
Decides whether and when to retry a failed request.
RetryPolicyInterface
Implemented by RetryPolicy in interceptors/retry/retry_policy.dart. Lets a RequestOptions carry a per-request retry policy with compile-time safety.
Schema
Light JSON Schema-like model used by ApiSpec.
SpecMockAdapter
Turns an ApiSpec into a fully-working mock adapter.
StreamingHttpAdapter
Optional capability an HttpAdapter may also implement to return an unbuffered response body via AdapterResponse.bodyStream.
Success<T>
Successful API result carrying the decoded body.
TestGenerator
Generates a complete, runnable *_test.dart from an ApiSpec.
TokenStorage
Interface for token persistence.
Utf8Charset
Default Charset backed by dart:convert's strict UTF-8 codec.

Enums

BackendFramework
Backend framework that BackendGuideGenerator emits code snippets for.
CacheMode
How a request interacts with the cache.
CircuitState
State of one circuit inside CircuitBreakerInterceptor.
GraphQLOperationKind
Kind of GraphQL operation.
QueryListFormat
How a List value is expanded into query-string pairs.
QueryNestedStyle
How a nested Map value is flattened into query-string keys.
ReplayOutcome
What happened to a single request during a replay pass.
ReplaySafety
Delivery guarantee for a queued request when a replay pass is interrupted.
ResponseType
Desired shape of the parsed response body.

Functions

buildQueryString(Map<String, dynamic> params, [QueryEncoder encoder = const QueryEncoder()]) → String
Builds a query string from a map.
buildUri({required String baseUrl, required String endpoint, Map<String, dynamic>? queryParameters, QueryEncoder encoder = const QueryEncoder()}) → Uri
Joins a base URL, endpoint and optional query parameters into a Uri.
compareQueuedRequests(QueuedRequest a, QueuedRequest b) → int
Default replay ordering: higher QueuedRequest.priority first, then oldest QueuedRequest.createdAt first, with QueuedRequest.id as a stable final tiebreak. Stores sort by this on OfflineQueueStore.drain; the replayer can override it with a custom comparator.

Typedefs

GraphQLDecoder<T> = T Function(Object data)
Decoder applied to the top-level data field.
MockResponder = Future<AdapterResponse> Function(AdapterRequest req)
Builds a canned response for a matched request.
ProgressCallback = void Function(int count, int? total)
Callback used for upload / download progress.
RefreshTokenFn = Future<bool> Function()
Async function that refreshes the access token. Returns true on success.
Transport = Future<AdapterResponse> Function(InterceptedRequest req)
The terminal network call the chain wraps: sends req and yields a response (or throws an ApiException).

Exceptions / Errors

ApiException
Typed exceptions used throughout the API client.
CancelError
Request was cancelled by the caller via a CancelToken.
GraphQLException
Thrown / surfaced when a GraphQL response contains errors.
HttpError
Server returned a non 2xx status code.
NetworkError
Low level I/O / DNS / socket failure.
ParseError
Failed to decode the response body.
PayloadTooLargeError
Request or response payload exceeded a configured byte limit.
TimeoutError
Request exceeded its Duration timeout.
UnknownError
Catch-all for anything else.