Fetch data from the internet
Refactor your application to use a robust, production-ready API client for the Wikipedia CLI.
In Chapter 3, you used the http package to make a simple request.
Now, you'll revisit HTTP to
build a robust, production-ready API client within the wikipedia package.
You'll learn how to handle query parameters,
map JSON responses to your data models, and
export these functions for use in your CLI.
What you'll accomplish
Prerequisites
#Before you begin this chapter, ensure you:
-
Have completed Chapter 11 and have a
working Dart development environment with the
dartpediaproject. - Understand basic networking concepts (like APIs and HTTP requests).
- Understand basic data serialization formats such as JSON.
Tasks
#
In this chapter, you'll move beyond simple scripts and
implement a proper API layer.
You'll work within the wikipedia package to
implement the API client logic, which
improves your application's scalability and maintainability.
Task 1: Add the http dependency to the wikipedia package
#
To make HTTP requests, you need to
add the http package as a dependency to the wikipedia package.
Open the
wikipedia/pubspec.yamlfile within your project.Locate the
dependenciessection.-
Add
http: ^1.3.0(or the latest stable version) underdependencies.wikipedia/pubspec.yamlyamldependencies: http: ^1.3.0 Save the
pubspec.yamlfile.Run
dart pub getin your terminal from thewikipediadirectory.
Task 2: Implement Wikipedia API calls
#Next, you'll create the API functions to fetch data from Wikipedia. You'll create three files:
-
summary.dart: This file will contain functions for retrieving article summaries. -
search.dart: This file will handle search queries to find articles. -
get_article.dart: This file will contain functions for fetching the full content of an article.
Create the directory
wikipedia/lib/src/api.Create the file
wikipedia/lib/src/api/summary.dart.-
Add the following code to
wikipedia/lib/src/api/summary.dart:wikipedia/lib/src/api/summary.dartdartimport 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import '../model/summary.dart'; Future<Summary> getRandomArticleSummary() async { final Uri url = Uri.https( 'en.wikipedia.org', '/api/rest_v1/page/random/summary', ); final http.Response response = await http.get(url); if (response.statusCode == 200) { final Map<String, Object?> jsonData = jsonDecode(response.body) as Map<String, Object?>; return Summary.fromJson(jsonData); } else { throw HttpException( '[WikipediaApiClient.getRandomArticleSummary] ' 'statusCode=${response.statusCode}, body=${response.body}', ); } } Future<Summary> getArticleSummaryByTitle(String articleTitle) async { final Uri url = Uri.https( 'en.wikipedia.org', '/api/rest_v1/page/summary/$articleTitle', ); final http.Response response = await http.get(url); if (response.statusCode == 200) { final Map<String, Object?> jsonData = jsonDecode(response.body) as Map<String, Object?>; return Summary.fromJson(jsonData); } else { throw HttpException( '[WikipediaApiClient.getArticleSummaryByTitle] ' 'statusCode=${response.statusCode}, body=${response.body}', ); } }This code defines two functions,
getRandomArticleSummaryandgetArticleSummaryByTitle, that build on the basic HTTP request you wrote in Chapter 3:getRandomArticleSummaryandgetArticleSummaryByTitle: Fetch a random article summary or a specific summary by interpolatingarticleTitleinto the endpoint path.- Typed JSON parsing:
Instead of returning a raw JSON string, both functions decode
response.bodywithjsonDecodeand pass the map toSummary.fromJsonto return a strongly typedSummaryobject. - Explicit failure handling:
When
response.statusCodeisn't200, the functions throw anHttpException(fromdart:io) rather than returning an error string, so callers can catch and handle failed requests withtry/catch.
Next create the file
wikipedia/lib/src/api/search.dart.-
Add the following code to
wikipedia/lib/src/api/search.dart:wikipedia/lib/src/api/search.dartdartimport 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import '../model/search_results.dart'; Future<SearchResults> search(String searchTerm) async { final Uri url = Uri.https( 'en.wikipedia.org', '/w/api.php', <String, Object?>{ 'action': 'opensearch', 'format': 'json', 'search': searchTerm, }, ); final http.Response response = await http.get(url); if (response.statusCode == 200) { final List<Object?> jsonData = jsonDecode(response.body) as List<Object?>; return SearchResults.fromJson(jsonData); } else { throw HttpException( '[WikipediaApiClient.search] ' 'statusCode=${response.statusCode}, ' 'body=${response.body}', ); } }This code defines the
searchfunction, which queries Wikipedia'sopensearchendpoint and returns aSearchResultsobject:- Query parameters:
Uri.httpsaccepts an optional third argument—aMapof query parameters (action,format, andsearch). Dart automatically formats these key-value pairs onto the URL and URL-encodes special characters like spaces insearchTerm. - List decoding:
Because the
opensearchendpoint returns a top-level JSON array,jsonDecode(response.body)is cast toList<Object?>before passing it toSearchResults.fromJson.
- Query parameters:
Create the file
wikipedia/lib/src/api/get_article.dart.-
Add the following code to
wikipedia/lib/src/api/get_article.dart:wikipedia/lib/src/api/get_article.dartdartimport 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import '../model/article.dart'; Future<List<Article>> getArticleByTitle(String title) async { final Uri url = Uri.https( 'en.wikipedia.org', '/w/api.php', <String, Object?>{ // order matters - explaintext must come after prop 'action': 'query', 'format': 'json', 'titles': title.trim(), 'prop': 'extracts', 'explaintext': '', }, ); final http.Response response = await http.get(url); if (response.statusCode == 200) { final Map<String, Object?> jsonData = jsonDecode(response.body) as Map<String, Object?>; return Article.listFromJson(jsonData); } else { throw HttpException( '[WikipediaApiClient.getArticleByTitle] ' 'statusCode=${response.statusCode}, ' 'body=${response.body}', ); } }This code defines
getArticleByTitle, which passes query parameters to/w/api.php(usingtitle.trim()to strip accidental leading or trailing whitespace) and parses the response into aList<Article>usingArticle.listFromJson.
Task 3: Export the API functions
#
Now that you've created the API functions,
export them and your existing models from the wikipedia library
so that the cli package can import and use them.
Open the
wikipedia/lib/wikipedia.dartfile.-
Replace the generated placeholder code in the file with the following
exportstatements:wikipedia/lib/wikipedia.dartdartexport 'src/api/get_article.dart'; export 'src/api/search.dart'; export 'src/api/summary.dart'; export 'src/model/article.dart'; export 'src/model/search_results.dart'; export 'src/model/summary.dart'; export 'src/model/title_set.dart';These
exportstatements make the API functions and models available to other packages that depend on thewikipediapackage.
Task 4: Verify with tests
#
Now that you've implemented the API functions and
updated the package dependencies,
run the tests you created in the previous chapter to confirm that
your changes haven't broken existing functionality in wikipedia.
Open your terminal and navigate to the
wikipedia/testdirectory.-
Remove the default test file by running
rm wikipedia_test.dart(on macOS or Linux) ordel wikipedia_test.dart(on Windows).dart creategenerated this file automatically to test the placeholder code you just replaced, so your project no longer needs it. Navigate back to the
wikipediadirectory.-
Run
dart test.You'll see output similar to the following, confirming that all your model tests pass:
bash00:02 +3: All tests passed!This confirms that the
wikipediapackage is working as expected.
Review
#What you accomplished
Here's a summary of what you built and learned in this lesson.Constructed complex URIs with query parameters
You used Uri.https() with a query parameter map to construct API URLs. This approach properly encodes special characters and handles complex query parameter combinations.
Created a production-ready API client
You implemented API functions that check HTTP status codes, throw an HttpException on failed requests, and map raw JSON responses to typed Dart objects.
Exported functions and types for reuse
You added export statements in wikipedia.dart to expose both the API functions and data model types. This creates a public library that your
cli package can import and use directly.
Quiz
#Check your understanding
1 / 3Uri.https?
-
Pass them as a third argument map:
Uri.https('api.com', '/search', {'q': 'dart'})That's right!
The third parameter accepts a
Map<String, dynamic>of query parameters. Dart handles URL encoding automatically. -
Append them to the path string:
Uri.https('api.com', '/search?q=dart')Not quite.
Query parameters in the path string work but aren't the cleanest approach.
-
Use string concatenation:
Uri.https('api.com', '/search') + '?q=dart'Not quite.
You can't concatenate strings to
Uriobjects using+.Uriprovides a different mechanism for adding query parameters. -
Call
.addQueryParam('q', 'dart')on theUriobject.Not quite.
Uriobjects are immutable and don't have anaddQueryParammethod. Query parameters must be specified differently.
http.get(url), how should you check if the request was successful?
-
Check if
response.statusCode == 200(or another success code).That's right!
HTTP status codes indicate success (200-299) or various failures (400s, 500s). Always check before processing the response body.
-
Check if
response.bodyis not empty.Not quite.
An empty body could be valid (like a 204 No Content). The body content alone doesn't tell you if the request succeeded.
-
Wrap the call in try/catch as successful requests don't throw.
Not quite.
HTTP errors (such as 404 and 500) don't throw exceptions by default. The request completes normally even when the server returns an error.
-
Check if
response.isSuccessreturns true.Not quite.
There's no
isSuccessproperty onResponse. You need to examine a different property of the response object.
HttpException instead of returning an error message string. Why is this a better practice for an API package?
-
It separates failure handling from valid data, letting functions return typed models (like
Summary) while callers handle errors withtry/catch.That's right!
Returning an error string doesn't fit a return type like
Future<Summary>and risks treating error text as article data. Throwing anHttpExceptionsignals failure explicitly so calling code can catch and handle it. -
Because
http.getcrashes the Dart runtime if you don't throw an exception on non-200 status codes.Not quite.
http.getcompletes normally with aResponseobject even for 404 or 500 status codes. ThrowingHttpExceptionis a deliberate design choice, not a runtime requirement. -
Throwing
HttpExceptionautomatically retries the failed network request up to three times.Not quite.
Throwing an exception stops execution of the function and propagates the failure to the caller; it doesn't retry the request.
-
Functions marked
asyncaren't allowed to return error strings when a network request fails.Not quite.
An
asyncfunction can return any declared type (such asFuture<String>, as in Chapter 3). Throwing an exception is preferred for type safety and structured error handling, not syntax rules.
Next lesson
#
In the next lesson, you'll complete your CLI application by
integrating the wikipedia package commands with the cli
package
and adding logging for debugging and error monitoring.
Unless stated otherwise, the documentation on this site reflects Dart 3.14.0. Page last updated on 2026-11-20. View source or report an issue.