Making HTTP Requests
Prerequisites: Working with JSON, Packages and pub
An API (Application Programming Interface) lets programs talk to
each other; most web APIs work over HTTP. The standard way to make
HTTP requests in Dart and Flutter is the http package.
dart pub add http
A GET request
import 'dart:convert';
import 'package:http/http.dart' as http;
class Repo {
final String fullName;
final int stars;
Repo(this.fullName, this.stars);
factory Repo.fromJson(Map<String, dynamic> json) =>
Repo(json['full_name'] as String, json['stargazers_count'] as int);
}
Future<Repo> fetchRepo(String name) async {
final response = await http
.get(Uri.https('api.github.com', '/repos/$name'))
.timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
throw Exception('Request failed: ${response.statusCode}');
}
return Repo.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
Future<void> main() async {
final repo = await fetchRepo('dart-lang/sdk');
print('${repo.fullName} has ${repo.stars} stars');
}
dart-lang/sdk has 10734 stars
(The number will be different when you run it.)
Uri.https(host, path)builds the address and encodes it correctly.- Always set a timeout, so a slow server can't hang your app.
- A 404 or 500 is a normal response, not an exception — check
statusCodeyourself. - Network failures (no connection) throw exceptions such as
SocketException/ClientException; catch them where you can show a helpful message.
POST with JSON
final response = await http.post(
Uri.https('httpbin.org', '/post'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'title': 'Hello'}),
);
print(response.statusCode);
Beyond the basics
For larger apps, the dio package adds interceptors (for example,
adding an auth token to every request), retries, and upload progress.
Common mistakes
- Hard-coding API keys in app code — anything shipped in an app can be extracted. Keep secrets on a server.
- Parsing the body without checking the status code first.