API service class
Data Layer
Summary
This lesson introduces the ApiService class as a centralized utility within the Data layer to handle all HTTP requests. By wrapping the Dio HTTP client, the application avoids redundant network configuration across multiple remote data sources and ensures that modifications to network behavior can be applied globally. The instructor demonstrates how to extract a base URL, configure environments in Postman for rapid testing, and implement a reusable get method that returns parsed JSON data.
Key Ideas
- ApiService centralizes network requests to prevent duplicating HTTP client configuration across multiple remote data sources.
- Dio is utilized as the underlying HTTP client package to perform requests and automatically handle statuses.
- Base URL is extracted to a final variable to simplify endpoint construction and adapt more easily to backend domain changes.
- Postman environments allow developers to store and switch base URLs without manually editing individual request URLs.
- The get method accepts an endPoint string and concatenates it with the base URL to execute the request.
- Dio automatically parses JSON responses, allowing the method to directly return the response data as a map.
Code Snippets
import 'package:dio/dio.dart';
class ApiService {
final Dio _dio;
final baseUrl = "https://www.googleapis.com/books/v1/";
ApiService(this._dio);
Future<Map<String, dynamic>> get({required String endPoint}) async {
var response = await _dio.get('$baseUrl$endPoint');
return response.data;
}
}Architecture Insight
ApiService is the thinnest possible wrapper over dio (or http, or whatever). Its job is to know the base URL and return decoded JSON. It does not know about BookModel, HomeRepo, or anything else feature-specific.
That thinness is deliberate. If ApiService ever grows a method called fetchFeaturedBooks, you've put feature logic in the wrong layer — the remote data source should call ApiService.get('volumes?...') and shape the result itself.
My Notes
The instructor creates a dedicated wrapper class for the Dio HTTP client. This is a solid architectural practice because it abstracts the specific HTTP package from the rest of the application; if Dio is ever replaced with the standard http package, only this isolated service file needs to change. The lesson hardcodes the baseUrl inside the ApiService. [Editor's note] For production-level applications, consider injecting the base URL into the constructor or using a package like flutter_dotenv to load it securely. Furthermore, the get method explicitly returns a Future<Map<String, dynamic>>. Because response.data in Dio is evaluated dynamically at runtime, this assumes the API will always return a JSON object (a Map). If a future endpoint returns a JSON array (a List), this strict return type will cause a runtime exception. A safer default might be returning dynamic or a generic wrapper.