LibraryFetching Data from Public APIs

Fetching Data from Public APIs

Learn about Fetching Data from Public APIs as part of Flutter App Development with Dart

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

code
http
package is the standard and most common way to make HTTP requests in Dart and Flutter. It provides a simple and efficient API for sending requests and handling responses.

What is the primary Dart package used for making HTTP requests in Flutter?

The http package.

To use the

code
http
package, you first need to add it as a dependency in your
code
pubspec.yaml
file:

yaml
dependencies:
flutter:
sdk: flutter
http:
# Add the latest version here
version: ^1.1.0

After adding it, run

code
flutter pub get
in your terminal.

Making a GET Request

The most common operation is fetching data using a GET request. The

code
http
package makes this straightforward. You'll typically use the
code
get()
function, which returns a
code
Future
that resolves to an
code
http.Response
object.

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):

dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
Future fetchData() 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

code
try-catch
blocks around your network requests is essential.

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

code
dart:convert
library's
code
jsonDecode()
function is the primary tool for this. For complex data structures, it's highly recommended to create Dart classes that mirror the JSON structure and use a JSON serialization package like
code
json_serializable
to automatically generate parsing code.

What Dart library is used to decode JSON strings?

dart:convert

Example of creating a Dart class for JSON parsing:

dart
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(Map json) {
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

code
FutureBuilder
widget. A
code
FutureBuilder
takes a
code
Future
and a builder function. The builder function is called whenever the Future completes, allowing you to build your UI based on the result (or show a loading indicator while waiting).

Example using

code
FutureBuilder
:

dart
FutureBuilder(
future: fetchPost(), // Your function that returns Future
builder: (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

Flutter HTTP Package Documentation(documentation)

Official documentation for the http package, covering basic usage, request methods, and response handling.

Flutter Networking: Fetching Data from the Internet(documentation)

Flutter's official guide on networking, explaining how to fetch data and handle responses.

Working with JSON in Dart(documentation)

Dart's official guide on how to encode and decode JSON data using the dart:convert library.

JSONPlaceholder - Fake Online REST API(documentation)

A free fake online REST API for testing and prototyping. Excellent for practicing API calls.

Flutter FutureBuilder Explained(blog)

A detailed explanation and examples of how to use the FutureBuilder widget to handle asynchronous operations.

Building a Flutter App with API Integration (YouTube Tutorial)(video)

A practical video tutorial demonstrating how to integrate with a public API in a Flutter application.

Understanding HTTP Status Codes(documentation)

Comprehensive reference for HTTP status codes, essential for understanding API responses.

JSON Serializable for Dart(documentation)

Information on using the json_serializable package to automate JSON serialization and deserialization in Dart.

REST API Tutorial for Beginners(video)

A beginner-friendly tutorial explaining the concepts of REST APIs and how they work.

The Anatomy of an HTTP Request(blog)

Explains the components of an HTTP request and response, providing foundational knowledge for API interaction.