Fetching Data from Public APIs in Flutter
Mobile applications often need to display dynamic information, which is typically fetched from external sources called Application Programming Interfaces (APIs). Public APIs provide a way for developers to access data without needing to build their own backend infrastructure. This module will guide you through the process of integrating with public APIs in your Flutter applications using Dart.
Understanding APIs and HTTP Requests
An API acts as a messenger that takes requests from one application, tells a system what to do, and then returns the response to the application. In mobile development, we commonly use HTTP (Hypertext Transfer Protocol) requests to communicate with APIs. Common HTTP methods include GET (to retrieve data), POST (to send data), PUT (to update data), and DELETE (to remove data).
APIs are the backbone of dynamic mobile apps, enabling data retrieval from external services.
APIs allow your Flutter app to talk to servers and get information like weather updates, news articles, or user data. This communication happens using standard web protocols like HTTP.
When your Flutter app needs to display real-time data, it sends an HTTP request to a specific API endpoint (a URL). The API server processes this request and sends back a response, usually in a structured format like JSON (JavaScript Object Notation). Your app then parses this JSON data and displays it to the user. This process is fundamental to creating interactive and data-rich mobile experiences.
The `http` Package in Dart
Flutter, being built on Dart, leverages Dart's ecosystem for network operations. The
http
The http
package.
To use the
http
pubspec.yaml
dependencies:flutter:sdk: flutterhttp:# Add the latest version hereversion: ^1.1.0
After adding it, run
flutter pub get
Making a GET Request
The most common operation is fetching data using a GET request. The
http
get()
Future
http.Response
The http.Response
object contains crucial information about the server's reply, including the status code (e.g., 200 for success, 404 for not found) and the response body, which is usually a string representing the data (often JSON). You'll need to parse this JSON string into a Dart object for use in your app. The dart:convert
library, specifically jsonDecode()
, is used for this.
Text-based content
Library pages focus on text content
Here's a basic example of fetching data from a public API (e.g., JSONPlaceholder):
import 'package:flutter/material.dart';import 'package:http/http.dart' as http;import 'dart:convert';FuturefetchData() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));if (response.statusCode == 200) {// If the server returns a 200 OK response, parse the JSON.final data = jsonDecode(response.body);print('Data fetched: ${data['title']}');} else {// If the server did not return a 200 OK response, throw an exception.throw Exception('Failed to load data');}}// In your widget:// ElevatedButton(onPressed: fetchData, child: Text('Fetch Data'))
Handling API Responses and Errors
Robust applications must handle potential errors gracefully. This includes network issues, server errors (non-200 status codes), and invalid data formats. Using
try-catch
Always check the statusCode
of the http.Response
. A status code of 200 generally indicates success, but other codes (like 201 for created, 204 for no content) can also be successful depending on the API.
Consider scenarios where the API might return an empty list or malformed JSON. Your parsing logic should account for these possibilities to prevent app crashes.
Parsing JSON Data
Once you have the JSON string from the API response, you need to convert it into Dart objects. The
dart:convert
jsonDecode()
json_serializable
dart:convert
Example of creating a Dart class for JSON parsing:
class Post {final int userId;final int id;final String title;final String body;Post({required this.userId, required this.id, required this.title, required this.body});factory Post.fromJson(Mapjson) { return Post(userId: json['userId'],id: json['id'],title: json['title'],body: json['body'],);}}// Usage:// final post = Post.fromJson(jsonDecode(response.body));
Displaying Fetched Data in Flutter UI
To display data fetched from an API in your Flutter UI, you'll typically use a
FutureBuilder
FutureBuilder
Future
Example using
FutureBuilder
FutureBuilder( future: fetchPost(), // Your function that returns Futurebuilder: (context, snapshot) {if (snapshot.hasData) {return Text(snapshot.data!.title);} else if (snapshot.hasError) {return Text('${snapshot.error}');}// By default, show a loading spinner.return const CircularProgressIndicator();},)
Learning Resources
Official documentation for the http package, covering basic usage, request methods, and response handling.
Flutter's official guide on networking, explaining how to fetch data and handle responses.
Dart's official guide on how to encode and decode JSON data using the dart:convert library.
A free fake online REST API for testing and prototyping. Excellent for practicing API calls.
A detailed explanation and examples of how to use the FutureBuilder widget to handle asynchronous operations.
A practical video tutorial demonstrating how to integrate with a public API in a Flutter application.
Comprehensive reference for HTTP status codes, essential for understanding API responses.
Information on using the json_serializable package to automate JSON serialization and deserialization in Dart.
A beginner-friendly tutorial explaining the concepts of REST APIs and how they work.
Explains the components of an HTTP request and response, providing foundational knowledge for API interaction.