REST APIs
suggest changeRepresentational State Transfer (REST) is the standard architectural style for building interconnected web services. In the Dart and Flutter ecosystem, developers both consume REST APIs from client applications using package:http and build lightweight, high-performance REST APIs on the server using package:shelf and shelf_router.
Consuming REST APIs (package:http)
Add the http package to your pubspec.yaml:
dependencies:
http: ^1.2.1
1. Data Model with JSON Serialization
Define strongly typed domain classes with fromJson and toJson:
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'] as int,
title: json['title'] as String,
body: json['body'] as String,
);
}
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'body': body,
};
}
2. Performing CRUD Operations
Use a persistent http.Client instance to pool socket connections:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
class PostApiClient {
final String baseUrl;
final http.Client _client;
PostApiClient({required this.baseUrl, http.Client? client})
: _client = client ?? http.Client();
// GET: Fetch list of resources
Future<List<Post>> fetchPosts() async {
final response = await _client.get(
Uri.parse('$baseUrl/posts'),
headers: {'Accept': 'application/json'},
);
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(response.body);
return data.map((json) => Post.fromJson(json as Map<String, dynamic>)).toList();
} else {
throw HttpException('Failed to load posts (Status: ${response.statusCode})');
}
}
// POST: Create a new resource
Future<Post> createPost(String title, String body) async {
final response = await _client.post(
Uri.parse('$baseUrl/posts'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'title': title, 'body': body}),
);
if (response.statusCode == 201) {
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
throw HttpException('Failed to create post (Status: ${response.statusCode})');
}
}
// PUT / PATCH: Update an existing resource
Future<Post> updatePost(int id, String title) async {
final response = await _client.patch(
Uri.parse('$baseUrl/posts/$id'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'title': title}),
);
if (response.statusCode == 200) {
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
throw HttpException('Failed to update post $id');
}
}
// DELETE: Remove a resource
Future<void> deletePost(int id) async {
final response = await _client.delete(Uri.parse('$baseUrl/posts/$id'));
if (response.statusCode != 200 && response.statusCode != 204) {
throw HttpException('Failed to delete post $id');
}
}
void close() => _client.close();
}
3. Handling Network Errors and Timeouts
Always guard HTTP calls with timeout constraints and catch socket or protocol exceptions:
import 'dart:async';
import 'dart:io';
Future<void> safeApiCall(PostApiClient client) async {
try {
final posts = await client.fetchPosts().timeout(const Duration(seconds: 10));
print('Fetched ${posts.length} posts.');
} on TimeoutException {
print('Request timed out. Please check your internet connection.');
} on SocketException catch (e) {
print('Network unreachable: ${e.message}');
} on HttpException catch (e) {
print('API Server Error: ${e.message}');
}
}
Building a REST API in Server-Side Dart (shelf)
With shelf and shelf_router, you can build clean microservices:
dependencies:
shelf: ^1.4.1
shelf_router: ^1.1.4
Complete REST Server Example
import 'dart:convert';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';
class UserApi {
final Map<int, Map<String, dynamic>> _users = {
1: {'id': 1, 'name': 'Alice', 'role': 'Admin'},
2: {'id': 2, 'name': 'Bob', 'role': 'Developer'},
};
Router get router {
final router = Router();
// GET /users - list all
router.get('/users', (Request req) {
return Response.ok(
jsonEncode(_users.values.toList()),
headers: {'Content-Type': 'application/json'},
);
});
// GET /users/<id> - get single
router.get('/users/<id|[0-9]+>', (Request req, String id) {
final user = _users[int.parse(id)];
if (user == null) {
return Response.notFound(jsonEncode({'error': 'User not found'}), headers: {'Content-Type': 'application/json'});
}
return Response.ok(jsonEncode(user), headers: {'Content-Type': 'application/json'});
});
// POST /users - create new
router.post('/users', (Request req) async {
final payload = await req.readAsString();
final body = jsonDecode(payload) as Map<String, dynamic>;
final newId = _users.keys.isEmpty ? 1 : _users.keys.last + 1;
final newUser = {'id': newId, 'name': body['name'], 'role': body['role'] ?? 'User'};
_users[newId] = newUser;
return Response(201, body: jsonEncode(newUser), headers: {'Content-Type': 'application/json'});
});
// DELETE /users/<id> - delete
router.delete('/users/<id|[0-9]+>', (Request req, String id) {
final removed = _users.remove(int.parse(id));
if (removed == null) {
return Response.notFound(jsonEncode({'error': 'User not found'}));
}
return Response(204); // No Content
});
return router;
}
}
void main() async {
final api = UserApi();
final handler = const Pipeline()
.addMiddleware(logRequests())
.addHandler(api.router.call);
final server = await io.serve(handler, 'localhost', 8080);
print('REST API listening on http://${server.address.host}:${server.port}');
}
Best Practices
- Reuse
http.Client(): Reusing anhttp.Clientkeeps underlying TCP connections alive via HTTP keep-alive, significantly speeding up subsequent requests. - Always specify timeouts: Unbounded network requests can hang app threads indefinitely during network brownouts.
- Follow HTTP status semantics: Use 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request), 401 (Unauthorized), 404 (Not Found), and 500 (Internal Server Error) consistently.
- Set
Content-Type: application/json: Always declare JSON content headers on both incoming and outgoing payloads.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents