Sub topic 2
Creating, updating and deleting resources
This chapter assumes you have the http package installed, know how Future and async/await work, and can read the FutureBuilder setup from earlier chapters. Each request method has a different job. POST creates a resource, PUT replaces it, PATCH changes some fields, and DELETE removes it.
Sending JSON with POST, PUT, PATCH and DELETE
A request body is the JSON payload sent to the server. The Content-Type header tells the server how to read it. The Authorization header carries a token that identifies the caller.
Map<String, String> _headers({String? token, bool json = false}) => {
'Accept': 'application/json',
if (json) 'Content-Type': 'application/json; charset=UTF-8',
if (token != null) 'Authorization': 'Bearer $token',
};Handling errors and timeouts
A non-2xx status means the server rejected the request. A timeout or ClientException means the request never got a usable reply. The helper below turns all three into one ApiException.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
@override
String toString() => 'ApiException($statusCode): $message';
}
Future<http.Response> _send(Future<http.Response> Function() request) async {
try {
final response = await request().timeout(const Duration(seconds: 10));
if (response.statusCode < 200 || response.statusCode >= 300) {
throw ApiException('Request failed', statusCode: response.statusCode);
}
return response;
} on TimeoutException {
throw const ApiException('The request timed out');
} on http.ClientException catch (e) {
throw ApiException('Connection problem: ${e.message}');
}
}Retrying safely
Retrying repeats a request after a failure. GET, PUT and DELETE are safe to repeat because repeating them leaves the same result on the server. POST is not. A POST that timed out may have created the resource already, so a retry can create a duplicate. Retry only on timeouts, connection problems, 429 and 5xx responses, and wait longer after each attempt.
Future<http.Response> withRetry(
Future<http.Response> Function() request, {
int attempts = 3,
}) async {
for (var attempt = 1;; attempt++) {
try {
return await _send(request);
} on ApiException catch (e) {
final retryable = e.statusCode == null ||
e.statusCode == 429 ||
e.statusCode! >= 500;
if (!retryable || attempt >= attempts) rethrow;
await Future<void>.delayed(Duration(milliseconds: 300 * (1 << (attempt - 1))));
}
}
}
Future<void> main() async {
final client = http.Client();
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/1');
try {
final response = await withRetry(() => client.put(
uri,
headers: _headers(token: 'demo-token', json: true),
body: jsonEncode({'id': 1, 'title': 'updated', 'userId': 1}),
));
print(response.statusCode);
} on ApiException catch (e) {
print(e);
} finally {
client.close();
}
}Exercise
Why should a POST request not go through withRetry?
Show answer
A POST usually creates a new resource. If the reply is lost, a retry can create a duplicate. Retry POST only when the server supports an idempotency key that makes repeated requests safe.