json_rest_client 0.3.0
json_rest_client: ^0.3.0 copied to clipboard
A small, dependency-light JSON HTTP client with typed exceptions, pluggable auth token storage, user-agent injection, and refresh-on-401 retry with a single-flight refresh lock.
json_rest_client #
A small JSON HTTP client for Dart. It gives you typed exceptions, pluggable
auth token storage, user-agent injection and refresh-on-401 retry. It wraps
package:http and removes repeated
response-decoding and error-mapping code from your networking layer.
Features #
get,post,put,patchanddeletehelpers that JSON-decode response bodiessendRawfor status and bytes access without decoding- Typed exceptions for network, timeout, HTTP status and deserialization failures
- Auth tokens from a host-provided
TokenStore - Single-flight token refresh on
401or403, then one retry RetryPolicywith exponential backoff, jitter andRetry-Aftersupport- Sync
onRequest,onResponseandonErrorhooks for every exchange - Case-insensitive header merging with per-call overrides
- Configurable base URL, timeout, auth scheme, token key and headers
CancelTokenfor cancelling in-flight requestssendStreamfor streaming response bodies chunk by chunkendpointfor a typed, reusable handle per path
Install #
dart pub add json_rest_client
Quick start #
import 'package:json_rest_client/json_rest_client.dart';
class InMemoryTokenStore implements TokenStore {
String? token;
@override
Future<String?> read(String key) async => token;
}
Future<void> main() async {
final client = JsonRestClient(
baseUrl: 'https://api.example.com/v1/',
tokenStore: InMemoryTokenStore()..token = 'secret',
);
final user = await client.get<Map<String, dynamic>>('users/1', auth: true);
print(user);
client.close();
}
In a Flutter app, back the TokenStore with flutter_secure_storage. Create
one JsonRestClient per base URL and keep it for the lifetime of the app.
Configuration #
| Parameter | Default | Purpose |
|---|---|---|
baseUrl |
required | Prefix for every request path. A trailing / is added when missing. |
client |
null |
Injected http.Client. close() leaves it open. |
tokenStore |
required | Reads the token for auth: true requests. |
onUnauthorized |
null |
Refreshes the token after a 401 or 403. |
userAgentProvider |
null |
Supplies the user-agent header. The value is lowercased. |
authScheme |
'Bearer' |
Scheme in the authorization header. |
authTokenKey |
'token' |
Key for TokenStore.read. |
defaultHeaders |
const {} |
Headers for every request. |
timeout |
30 seconds | Default timeout for one exchange. |
retryPolicy |
null |
Retries transient failures. null disables retries. |
onRequest |
null |
Runs before every HTTP exchange. |
onResponse |
null |
Runs after every exchange that receives a response. |
onError |
null |
Runs after every exchange that fails with an error. |
Requests #
The request helpers resolve path relative to baseUrl and return the
decoded body as T?, or null for an empty successful body:
final List<dynamic> items = await client.get<List<dynamic>>('items');
final Map<String, dynamic> created = await client.post<Map<String, dynamic>>(
'items',
body: {'name': 'bolt'},
auth: true,
);
put, patch and delete complete the set. put and patch take a body
like post; delete takes no body:
await client.put<Map<String, dynamic>>(
'items/7',
body: {'name': 'nut'},
);
await client.patch<Map<String, dynamic>>(
'items/7',
body: {'price': 12},
);
await client.delete<Map<String, dynamic>>('items/7');
put and delete are idempotent, so a RetryPolicy retries them. patch
is not idempotent and is retried only with retryNonIdempotent. A body sent
with any method gets the JSON content type unless you override the header.
Pass a decoder to build T from the decoded JSON. Pass query parameters
with query. Don't put a query string in path. A per-call timeout
overrides the default.
sendRaw returns a RestResponse for every status and doesn't throw for
non-success statuses:
final RestResponse response = await client.sendRaw(
'GET',
path: 'items',
maxResponseBytes: 1000000,
);
print(response.statusCode);
print(response.headers);
print(response.body);
Streaming responses #
sendStream returns the status and headers with the response and leaves the
body as a stream:
final response = await client.sendStream('GET', path: 'events');
print(response.statusCode);
await for (final chunk in response.body) {
print(utf8.decode(chunk));
}
Every status comes back as-is, like sendRaw. Retries aren't attempted after
the response headers arrive.
Typed endpoints #
endpoint keeps the path, the decoder, the auth flag and extra headers in one
handle:
final items = client.endpoint<Map<String, dynamic>>(
'items',
decoder: (json) => json as Map<String, dynamic>,
auth: true,
);
final page = await items.get(query: {'page': '2'});
await items.post({'name': 'bolt'});
await items.put({'name': 'nut'});
await items.delete();
Cancellation #
Pass one CancelToken to several calls and cancel them together:
final token = CancelToken();
final request = client.sendStream('GET', path: 'events', cancelToken: token);
token.cancel(); // the call throws RequestCancelledException
A token that is already cancelled makes the call throw before it sends.
Retries #
Pass a RetryPolicy to retry transient failures:
final client = JsonRestClient(
baseUrl: 'https://api.example.com/v1/',
tokenStore: tokenStore,
retryPolicy: const RetryPolicy(
maxAttempts: 4,
baseDelay: Duration(milliseconds: 300),
),
);
maxAttempts counts every attempt, including the first one. The client
retries NetworkException failures and responses with a status in
retryableStatuses (429, 500, 502, 503, 504 by default). Retries
apply to GET, HEAD, PUT and DELETE. Set retryNonIdempotent: true to
retry POST and other methods. Timeouts are never retried.
The delay grows exponentially with jitter. The first retry waits between
baseDelay and 2 * baseDelay. A Retry-After response header with a whole
number of seconds overrides the computed delay. Call
RetryPolicy.delayFor(attempt, retryAfterHeader) to compute the delay for one
attempt.
Without retryPolicy, the client makes one attempt per exchange.
Interceptors #
The client calls three optional hooks around every HTTP exchange, including each retry attempt and each refresh retry:
final client = JsonRestClient(
baseUrl: 'https://api.example.com/v1/',
tokenStore: tokenStore,
onRequest: (method, url) => print('-> $method $url'),
onResponse: (method, url, status, duration) =>
print('<- $status $method $url in $duration'),
onError: (method, url, error, duration) =>
print('!! $error $method $url in $duration'),
);
Every exchange starts with one onRequest call and ends with exactly one
onResponse or onError call. onResponse reports every HTTP status,
including error statuses that the client maps to exceptions afterwards.
onError reports network and timeout failures. Exceptions from a hook
propagate to the caller.
Timeouts #
The timeout constructor parameter sets the default timeout for one HTTP
exchange, 30 seconds by default. Every request method accepts a timeout
override:
await client.get('slow-report', timeout: const Duration(minutes: 2));
final health = await client.sendRaw(
'GET',
path: 'health',
timeout: const Duration(seconds: 2),
);
A timeout throws RequestTimeoutException and never triggers a retry.
Auth and refresh #
With auth: true, the client reads tokenStore.read(authTokenKey) and sends
authorization: <authScheme> <token>. When there's no token, it leaves the
header out.
When a response is 401 or 403:
- Without
onUnauthorized, the client throws anUnauthorizedException. - Concurrent unauthorized responses on one client share one refresh. The callback runs once per burst.
- The returned token is used for one retry of the original request.
- A
null, empty or still-unauthorized result throws anUnauthorizedException.
The client doesn't write the new token back. Store it in your TokenStore so
later requests use it.
Headers #
Header names match case-insensitively. Later entries win in this order:
defaultHeadersfrom the constructor.- The computed
user-agentandauthorizationheaders. - The default
content-type: application/jsonforPOSTrequests. - Per-call
headers.
Exceptions #
Every failure that the client detects throws a subtype of the sealed
RestClientException:
| Exception | Condition |
|---|---|
NetworkException |
A SocketException or http.ClientException occurred. |
RequestTimeoutException |
The exchange exceeded the timeout. |
BadRequestException |
The server returned 400. |
UnauthorizedException |
401 or 403 with no usable refresh token, or the retry was still unauthorized. |
NotFoundException |
The server returned 404. |
ConflictDataException |
The server returned 409. |
InvalidInputException |
The server returned 422. |
ServerErrorException |
The server returned 500 or any other non-2xx status. |
DeserializationException |
The body was not valid JSON, or the cast to T failed. |
ResponseLimitException |
sendRaw exceeded maxResponseBytes. |
RequestCancelledException |
A cancel token cancelled the request. |
For HTTP status errors, message holds the raw response body. The fallback
'HTTP <status>' is used only when the body is empty. Errors from
caller-supplied callbacks propagate unchanged.
Client ownership #
close() releases the http.Client that the constructor created. When you
inject a client through the client parameter, close() does nothing and the
client stays yours. Don't use the instance after close().
Platform support #
The package imports dart:io to detect SocketException. It supports mobile,
desktop and server apps. Web is not supported.
Example #
See example/main.dart for a runnable CLI.