Http
In this chapter, you'll implement the core functionality of the Wikipedia CLI by making API calls to retrieve data. You'll add the http
package as a dependency, create API functions, and then export those functions so they can be used by the cli
package.
Prerequisites
#Before you begin this chapter, ensure you:
- Have completed Chapter 10 and have a working Dart development environment with the
dartpedia
project. - Understand basic networking concepts (like APIs and HTTP requests).
- Understand basic data serialization formats such as JSON.
Tasks
#In this chapter, you'll add the core functionality of the Wikipedia CLI by making API calls to retrieve data. You'll work within the wikipedia
package to implement the API client logic.
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.yaml
file within your project.Locate the
dependencies
section.Add
http: ^1.3.0
(or the latest stable version) underdependencies
.yamldependencies: http: ^1.3.0
Save the
pubspec.yaml
file.Run
dart pub get
in your terminal from thewikipedia
directory.
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
:dartimport 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import '../model/summary.dart'; Future<Summary> getRandomArticleSummary() async { final http.Client client = http.Client(); try { final Uri url = Uri.https( 'en.wikipedia.org', '/api/rest_v1/page/random/summary', ); final http.Response response = await client.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( '[WikipediaDart.getRandomArticle] ' 'statusCode=${response.statusCode}, body=${response.body}', ); } } on FormatException { // todo: log exceptions rethrow; } finally { client.close(); } } Future<Summary> getArticleSummaryByTitle(String articleTitle) async { final http.Client client = http.Client(); try { final Uri url = Uri.https( 'en.wikipedia.org', '/api/rest_v1/page/summary/$articleTitle', ); final http.Response response = await client.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( '[WikipediaDart.getArticleSummary] ' 'statusCode=${response.statusCode}, body=${response.body}', ); } } on FormatException { // todo: log exceptions rethrow; } finally { client.close(); } }
This code defines two functions:
getRandomArticleSummary
andgetArticleSummaryByTitle
. Both functions use thehttp
package to make GET requests to the Wikipedia API and return aSummary
object.getRandomArticleSummary
fetches a summary for a random article, whilegetArticleSummaryByTitle
fetches a summary for a specific article title.Next create the file
wikipedia/lib/src/api/search.dart
.Add the following code to
wikipedia/lib/src/api/search.dart
:dartimport 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import '../model/search_results.dart'; Future<SearchResults> search(String searchTerm) async { final http.Client client = http.Client(); try { final Uri url = Uri.https( 'en.wikipedia.org', '/w/api.php', <String, Object?>{ 'action': 'opensearch', 'format': 'json', 'search': searchTerm, }, ); final http.Response response = await client.get(url); if (response.statusCode == 200) { final List<Object?> jsonData = jsonDecode(response.body) as List<Object?>; return SearchResults.fromJson(jsonData); } else { throw HttpException( '[WikimediaApiClient.getArticleByTitle] ' 'statusCode=${response.statusCode}, ' 'body=${response.body}', ); } } on FormatException { rethrow; } finally { client.close(); } }
This code defines the
search
function, which uses thehttp
package to make a GET request to the Wikipedia API'sopensearch
endpoint and returns aSearchResults
object. Theopensearch
endpoint is used to search for Wikipedia articles based on a search term.Create the file
wikipedia/lib/src/api/get_article.dart
.Add the following code to
wikipedia/lib/src/api/get_article.dart
:dartimport 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import '../model/article.dart'; Future<List<Article>> getArticleByTitle(String title) async { final http.Client client = http.Client(); try { 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 client.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( '[ApiClient.getArticleByTitle] ' 'statusCode=${response.statusCode}, ' 'body=${response.body}', ); } } on FormatException { // TODO: log rethrow; } finally { client.close(); } }
This code defines the
getArticleByTitle
function, which uses thehttp
package to make a GET request to the Wikipedia API and returns aList<Article>
object. This function retrieves the content of a Wikipedia article based on its title.
Task 3: Export the API functions
#Now that you've created the API functions, you need to export them from the wikipedia
library so they can be used by the cli
package. You'll also export the existing models.
Open the
wikipedia/lib/wikipedia.dart
file.Add the following
export
statements to the file:dartexport '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
export
statements make the API functions and models available to other packages that depend on thewikipedia
package.
Task 4: Verify with tests
#Now that you have implemented the API functions and updated the package dependencies, it's good practice to run the tests you created in the previous chapter. This will confirm that your changes have not broken the existing functionality of the wikipedia
package.
Open your terminal and navigate to the
wikipedia/test
directory.Remove the default test file by running the command
rm wikipedia_test.dart
(on macOS or Linux) ordel wikipedia_test.dart
(on Windows). This file was generated automatically but is not used in our project.Open your terminal and navigate to the
wikipedia
directory.Run the command
dart test
.You should see output similar to this, confirming all your existing tests still pass:
bash00:02 +3: All tests passed! This confirms that the wikipedia package is still working as expected.
Review
#In this chapter, you learned how to:
- Add a package dependency to
pubspec.yaml
. - Construct
Uri
objects for API requests. - Make HTTP GET requests using the
http
package. - Handle API responses and decode JSON data.
- Export functions and models from a Dart library.
Quiz
#Question 1: Which file is used to manage dependencies in a Dart project?
- A)
main.dart
- B)
pubspec.yaml
- C)
README.md
- D)
LICENSE
Question 2: Which Dart library is used to make HTTP requests?
- A)
dart:io
- B)
dart:convert
- C)
package:http
- D)
package:async
Question 3: What is the purpose of the export
statement in a Dart library?
- A) To hide declarations from other libraries.
- B) To make declarations available to other libraries.
- C) To specify the version of the Dart SDK required by the library.
- D) To define the entry point of the library.
Next lesson
#In the next lesson, you'll complete the CLI by integrating the wikipedia
package with the cli
package. You'll implement the command logic and display the results to the user.
Unless stated otherwise, the documentation on this site reflects Dart 3.9.0. Page last updated on 2025-08-18. View source or report an issue.