๐ Lesson 11: Fetch Live Data
The Complete Data Pipeline: Internet โ Your App
๐ง Your CLI app can talk to the entire internet using HTTP requests
With the package:http package, Dart can send HTTP requests to any REST API, receive JSON responses, and integrate live data into your application. The official tutorial uses the Wikipedia API as a real-world example.
package:http
+ Model Class
HTTP Requests with package:http
๐ง The http package provides simple functions for all HTTP methods
Add package:http to your pubspec.yaml dependencies. Then use http.get(), http.post(), http.put(), or http.delete() to make requests. Each returns a Future<Response>.
Setting Up
# pubspec.yaml
dependencies:
http: ^1.3.0
Making a GET Request โ Line by Line
// 1. Import the http package
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> fetchData() async {
// 2. Build the URL using Uri.parse()
final url = Uri.parse(
'https://api.example.com/data'
);
// 3. Send the GET request (returns Future<Response>)
final response = await http.get(url);
// 4. Check if the request succeeded
if (response.statusCode == 200) {
// 5. Decode the JSON body
final data = jsonDecode(response.body);
print(data);
} else {
// 6. Handle failure
print('Request failed: \${response.statusCode}');
}
}
๐ Breakdown
as http for clarityasync โ network is asyncUri.parse() creates a valid URI objectawait pauses until response arrivesstatusCode first!jsonDecode converts body to Map/ListstatusCode (int), body (String), headers (Map), and isRedirect (bool). Always check statusCode before using body.
The Official Tutorial โ Fetching from Wikipedia
๐ This complete example comes directly from the official Dart fetch-data tutorial
The official tutorial demonstrates fetching live data from Wikipedia's REST API. Below is the complete example with explanations.
๐ง The Wikipedia REST API provides article summaries at a simple URL pattern
The URL pattern is: https://en.wikipedia.org/api/rest_v1/page/summary/ARTICLE_TITLE. You replace ARTICLE_TITLE with the Wikipedia page title (spaces become underscores).
The Complete Wikipedia Fetch Example (from the official tutorial)
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> main() async {
// The Wikipedia page we want
final title = 'Dart_(programming_language)';
// Build the API URL
final url = Uri.parse(
'https://en.wikipedia.org/api/rest_v1/page/summary/\$title'
);
// Make the HTTP GET request
final response = await http.get(url);
// Check if successful
if (response.statusCode == 200) {
// Parse the JSON response
final data = jsonDecode(response.body);
// Extract and display the title and extract
print('๐ \${data['title']}');
print('\${data['extract']}');
} else {
print('Failed to load article: \${response.statusCode}');
}
}
๐ What This Code Does
main() async โ entry point is asyncUri.parse() validates and creates URIawait http.get(url) โ the actual network calljsonDecode(response.body) parses JSONdata['title'] and data['extract']What the Wikipedia API Returns
{
"title": "Dart (programming language)",
"displaytitle": "Dart",
"pageid": 33033735,
"extract": "Dart is a programming language developed by Google...",
"extract_html": "<p>Dart is a programming language...</p>",
"thumbnail": {
"source": "https://upload.wikimedia.org/...",
"width": 320
},
"content_urls": {
"desktop": {
"page": "https://en.wikipedia.org/wiki/Dart_(programming_language)"
}
}
}
title (the article title), extract (a plain-text summary of the article โ perfect for CLI display), and content_urls.desktop.page (link to the full article).
๐งช Simulate: Fetch a Wikipedia Article
Understanding HTTP Status Codes
๐ง Every HTTP response includes a 3-digit status code that tells you what happened
Codes are grouped by the first digit: 2xx = success, 3xx = redirect, 4xx = client error (your fault), 5xx = server error (their fault). Always check the status code before processing the response body.
โ 2xx โ Success
Your request worked.
200 OK 201 Createdresponse.statusCode == 200
๐ 3xx โ Redirect
Resource moved elsewhere.
301 Movedhttp package follows redirects automatically
โ 4xx โ Client Error
You made a mistake.
400 Bad Request 404 Not Found 429 Rate LimitedCheck your URL and parameters
๐ฅ 5xx โ Server Error
The server broke.
500 Internal Error 503 UnavailableRetry later with backoff
Error Handling & Retry Logic
๐ง Network requests can fail in many ways. Your app needs to handle them all.
Network errors (no connection), timeouts, rate limiting, and server errors all require different handling strategies. The most robust approach is retry with exponential backoff.
Common Network Errors and How to Handle Them
try {
final response = await http.get(url)
.timeout(Duration(seconds: 10));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else if (response.statusCode == 404) {
throw NotFoundException('Article not found');
} else if (response.statusCode == 429) {
print('Rate limited โ waiting before retry');
await Future.delayed(Duration(seconds: 60));
return fetchData(); // Retry after waiting
} else {
throw HttpException('Server error: \${response.statusCode}');
}
} on TimeoutException {
print('Request timed out โ check your connection');
} on SocketException {
print('No internet connection');
}
Retry with Exponential Backoff
Future<T> fetchWithRetry<T>(
Future<T> Function() request,
{int maxRetries = 3}
) async {
for (int attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await request()
.timeout(Duration(seconds: 10));
} catch (e) {
if (attempt == maxRetries) rethrow;
// Wait longer each attempt: 2s, 4s, 8s
final delay = Duration(seconds: 2 * attempt);
await Future.delayed(delay);
print('Retry \$attempt/\$maxRetries after \${delay.inSeconds}s');
}
}
}
๐ How It Works
try the request with a timeoutrethrow on final attempt โ gives up๐งช Simulate Network Scenarios
Putting It All Together โ A Complete Wikipedia Client
๐ง Combining HTTP requests, JSON parsing, status code handling, and retry logic into a reusable function
import 'dart:convert';
import 'package:http/http.dart' as http;
class WikipediaClient {
static const _baseUrl = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
/// Fetches a Wikipedia article summary
Future<Map<String, dynamic>> fetchArticle(String title) async {
final url = Uri.parse('\$_baseUrl\$title');
try {
final response = await http.get(url)
.timeout(Duration(seconds: 10));
return switch (response.statusCode) {
200 => jsonDecode(response.body),
404 => throw Exception('Article not found: \$title'),
_ => throw HttpException('HTTP \${response.statusCode}'),
};
} on TimeoutException {
throw Exception('Request timed out');
} on SocketException {
throw Exception('No internet connection');
}
}
}
// Usage in main()
Future<void> main() async {
final client = WikipediaClient();
try {
final article = await client.fetchArticle('Dart_(programming_language)');
print('๐ \${article['title']}');
print(article['extract']);
} catch (e) {
print('โ Error: \$e');
}
}
๐ฏ Fetch Data Quiz
Score: 0/5 | Hints: 3
Loading question...
Practice Projects
Apply what you've learned by building these hands-on projects.