How to Fetch Data from REST APIs in Flutter

To show album details, a Flutter screen needs the album data from a server. Fetching from a REST API means sending an HTTP request and using the server’s response in the app.

I’ll show how to fetch and display album data with FutureBuilder, and how to handle request errors.

TL;DR

Use the http package to request a REST endpoint, convert its JSON into typed Dart objects, and render the returned Future with FutureBuilder.

  • Add the dependency with the flutter pub add http command.
  • Check the HTTP status before decoding the body.
  • Create the Future once in initState, not from build.
  • Render waiting, error, empty and populated states separately.

What Does Fetching a REST API Mean in Flutter?

Fetching means sending an HTTP request to a server and using its response in the app. A GET request asks the server to return a resource, often as JSON.

The http package returns a Future because network work finishes later. A response includes a status code and a body.

This walkthrough uses the JSONPlaceholder album endpoint, which returns one JSON object with userId, id and title fields. For a collection endpoint, the outer JSON value is instead a list, so each element must be mapped to a model.

The endpoint URL names the resource, while the method communicates the operation.

JSON is text with objects, arrays, strings, numbers, booleans and null values. Dart’s decoder returns dynamic values because the shape depends on the response.

How to Fetch and Display REST API Data in Flutter

A reliable basic flow is dependency, model, request function, then widget state. Keep the request Future outside build so incidental rebuilds do not send another GET.

Step 1: Add the HTTP package and choose an endpoint

From the Flutter project directory, add the maintained http package and use an HTTPS endpoint you can inspect. The Flutter cookbook uses the package for simple requests, so this tutorial avoids adding a separate networking framework.

flutter pub add http

The command updates the project’s dependency configuration and resolves the package. Let pub choose a compatible release rather than copying an old version constraint from an older tutorial.

Run the command from the directory that contains pubspec.yaml. If Flutter reports that no project was found, move into the app directory first. After it completes, the package appears under dependencies in the project configuration and can be imported by Dart source files.

For an app you ship, use the API’s documented base URL and authentication method instead of embedding a private key in source code.

Step 2: Define a model for the JSON object

Album maps the endpoint’s userId, id and title values to typed Dart fields.

class Album {
  const Album({required this.userId, required this.id, required this.title});

  final int userId;
  final int id;
  final String title;

  factory Album.fromJson(Map<String, dynamic> json) {
    final userId = json['userId'];
    final id = json['id'];
    final title = json['title'];
    if (userId is! int || id is! int || title is! String) {
      throw const FormatException('Unexpected album response');
    }
    return Album(userId: userId, id: id, title: title);
  }
}

The factory converts one JSON map into an Album. A response with nested objects can use nested Dart types.

For this response, the model keeps the three values the screen uses and leaves unrelated response fields out.

Step 3: Request the resource and validate its response

Convert the endpoint string to a Uri, await http.get, check the status, then decode the body. A 404 or 500 response still arrives as an HTTP response, so status validation must happen before JSON parsing.

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Album> fetchAlbum() async {
  final uri = Uri.https('jsonplaceholder.typicode.com', '/albums/1');
  final response = await http.get(uri, headers: {'Accept': 'application/json'});
  if (response.statusCode != 200) {
    throw Exception('Album request failed: HTTP ${response.statusCode}');
  }
  final json = jsonDecode(response.body) as Map<String, dynamic>;
  return Album.fromJson(json);
}

Using Uri.https keeps the host, path and scheme explicit. The Accept header tells the server which representation the client expects. It does not replace checking the response status or validating the decoded shape.

The request function produces an Album for the screen to display.

JSON decoding can fail when the server returns HTML, an empty body or malformed JSON. Inspect the response body and the API documentation before changing the model.

Step 4: Store the Future outside build

Assign the request Future in initState, which runs when this State object is created.

late Future<Album> futureAlbum;

@override
void initState() {
  super.initState();
  futureAlbum = fetchAlbum();
}

Place this state field and override inside a StatefulWidget’s State class. A retry action assigns a new Future in setState.

Flutter separates a widget’s description from its mutable State object. That State object is disposed of when the screen is removed permanently.

The first frame can display a progress indicator while the network request is pending.

Step 5: Render loading, error and returned data

FutureBuilder connects the request Future to widget output and uses its snapshot to report whether work is waiting, completed with data, or completed with an error. The builder can return a different widget for each state.

FutureBuilder<Album>(
  future: futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Center(child: CircularProgressIndicator());
    }
    if (snapshot.hasError) {
      return const Center(child: Text('Could not load the album.'));
    }
    final album = snapshot.data;
    if (album == null) {
      return const Center(child: Text('No album was returned.'));
    }
    return ListTile(title: Text(album.title));
  },
)

A completed response replaces the progress indicator with data or an empty-state message.

For a list endpoint, decode the outer value as a List and convert each map with the map method. The request function then returns a Future containing a list of Album objects, and the widget can render those objects with ListView.builder.

ListView.builder creates rows as they are needed for the visible portion of a long collection. Give each row a stable key when the list can change order or items can be removed.

A refresh action can keep existing content visible while it requests updated data.

Handle HTTP Errors, Empty Data, and Platform Setup

When a screen does not show the expected result, identify which part of the request flow failed before changing the UI. A status, a transport exception, or a parsing error points to a different part of the flow.

CaseWhat to checkResponse in the app
Request throws or times outDevice connectivity, hostname and endpoint reachabilityShow a retryable network error
Status is not successfulHTTP status and API’s error responseDo not parse it as the expected model
JSON keys or types differActual response shape, including object versus listReport a parsing error and correct the mapping
Valid collection has no itemsDecoded list lengthShow an empty-state message

On Android, add the INTERNET permission to AndroidManifest.xml. macOS builds need the network client entitlement in both DebugProfile and Release entitlements.

When the screen remains blank, verify the URL from the running device or emulator, inspect the response status, and compare the JSON keys with Album.fromJson. On Flutter web, confirm that the API server allows the browser origin through CORS.

Top-level http.get suits a small request function. Use an injected http.Client when tests need a mock or a service makes several calls, and close it when its owner is finished.

A successful status does not guarantee the body has the shape the app expects.

A timeout or DNS lookup failure happens before a usable HTTP response exists, so show a network message and allow a retry. A 401 or 403 points to authentication or access rules. A 404 usually means the path or resource identifier needs checking.

An empty list can mean that the account has no records yet, so render a message that explains what the user can do next. A null response or missing required object has different meaning and should be handled according to the API contract.

During local debugging, log a concise error with the request path and failure category. Keep private response data out of diagnostics.

CORS permission comes from the API server, not from a header added to the app.

Platform setup errors can look like request failures even when the Dart function is correct. Check the target-specific permission or entitlement and rebuild after changing platform configuration.

Some APIs wrap returned data in a top-level object with a data field. Check the response documentation before choosing a decoder cast.

For protected endpoints, follow the API provider’s documented token flow and keep production credentials out of source files that ship to users.

Keep user-facing errors short and actionable. A connectivity problem can offer a retry, while an access-denied response may require signing in again. Parsing errors usually point to a mismatch between the API response and the model, so they are more useful in developer diagnostics than as raw text on screen.

Repeated requests can also matter when the server applies rate limits or the user pays for API usage. Use a clear refresh action when the data should be fetched again, and consider caching if the endpoint permits it.

When an API paginates results, one successful response may contain only the first page. Read the pagination fields in the response and request the next page when the user scrolls or selects a page. Keep the loading indicator for the next page separate from the initial screen load so existing rows remain useful.

For large responses, avoid decoding and building every row in a single UI operation when that work makes scrolling unresponsive. A paginated endpoint and lazily built list can limit the work. Measure on the target device before adding background parsing or a more complex data layer.

Check the request from the same kind of target where the app will run. A desktop development browser, an Android emulator and a physical iPhone can have different permissions, network paths or server restrictions. Reproduce the failure on the affected target before changing a model that already matches the response.

Conclusion: Keep the Request Outside the Widget Build

A Flutter REST request is a chain: GET a Uri, check the response, decode JSON into a typed model, and render the Future’s state.

For the official platform recipe, see Flutter’s fetch data cookbook and the http package documentation. If you are new to Flutter, continue with CodeForGeek’s Flutter getting started guide or its explanation of Flutter widgets.

FAQ

These answers cover common choices when adding an endpoint to a Flutter screen.

Which package can I use to fetch REST data in Flutter?

The http package is a cross-platform option for making HTTP requests. Add it with flutter pub add http, then call an endpoint with a Uri.

Why should I keep the Future outside build()?

Flutter can rebuild a widget often. Creating the request Future in build can start another request on rebuild, so store it in State, commonly from initState().

How do I handle a JSON array response?

Decode the body as a list, cast each element to Map, and map each element through the model’s fromJson factory.

Devdeep Ghosh
Devdeep Ghosh

Devdeep Ghosh covers Node.js development, including npm workflows, package configuration, Express troubleshooting, and server-side APIs. His work also covers concurrency and module systems.

Articles: 10