Skip to main content
Flutter Basics – Complete Beginner to Advanced Guide
CHAPTER 18 Beginner

API Integration and HTTP Requests

Updated: May 16, 2026
30 min read

# CHAPTER 18

API Integration and HTTP Requests

1. Introduction

A mobile app that doesn't connect to the internet is essentially a calculator. Modern applications rely on external servers to provide dynamic content: live weather updates, social media feeds, banking records, and e-commerce catalogs. To get this data, your app must communicate with a web server using an Application Programming Interface (API). In this chapter, we will master API Integration and HTTP Requests. We will install the official http package, learn how to handle delays using Dart's async/await, and successfully fetch data using GET requests and send data using POST requests.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Install the http package from pub.dev.
  • Understand asynchronous programming (Future, async, await).
  • Execute an HTTP GET request to fetch data from a REST API.
  • Execute an HTTP POST request to send data to a server.
  • Handle network errors (like 404 Not Found) gracefully in the UI.

3. Asynchronous Programming (The Concept)

When your app asks a server for data, it might take 2 seconds for the server to reply. If the app freezes for 2 seconds while waiting, the OS will flag the app as "Unresponsive" and crash it. To fix this, Dart uses Asynchronous Programming.
  • Future: A promise that data will arrive eventually.
  • async: A keyword placed on a function, telling Dart it might take a while.
  • await: A keyword telling Dart: *"Pause this specific function until the data arrives, but let the rest of the app keep running!"*

4. Setup and the http Package

  1. 1. Add the package to pubspec.yaml:
http: ^1.1.0
  1. 2. At the top of your Dart file, import it using an alias (standard practice):
import 'package:http/http.dart' as http;

5. Executing a GET Request (Fetching Data)

A GET request is used to retrieve data (like fetching a list of users). Let's fetch a random joke from a public API.
dart
1234567891011121314151617181920
// 1. Mark the function as async, returning a Future string
Future<String> fetchJoke() async {
  // 2. Define the URL
  final url = Uri.parse(&#039;https://official-joke-api.appspot.com/random_joke');
  
  try {
    // 3. AWAIT the network request!
    final response = await http.get(url);
    
    // 4. Check the Status Code (200 means OK/Success)
    if (response.statusCode == 200) {
      // Return the raw JSON string text
      return response.body; 
    } else {
      return "Server error: ${response.statusCode}";
    }
  } catch (e) {
    return "Failed to connect to the internet.";
  }
}

6. Executing a POST Request (Sending Data)

A POST request is used to create or send data (like logging in or submitting a form). You must send a body (the data) along with the request.
dart
1234567891011121314151617
Future<void> loginUser(String email, String password) async {
  final url = Uri.parse(&#039;https://example.com/api/login');
  
  final response = await http.post(
    url,
    body: {
      &#039;email': email,
      &#039;password': password,
    },
  );

  if (response.statusCode == 201) { // 201 means Created/Success
    print("Login successful!");
  } else {
    print("Login failed.");
  }
}

7. Integrating with the UI

How do we show the joke on the screen when it arrives? While there is a specialized widget called FutureBuilder, beginners should use setState()!
dart
12345678910111213141516171819
String jokeText = "Press the button to load a joke!";
bool isLoading = false; // Tracks if the network request is running!

void getJoke() async {
  // 1. Show the loading spinner
  setState(() { isLoading = true; }); 
  
  // 2. Wait for the API
  String result = await fetchJoke(); 
  
  // 3. Hide spinner and show text!
  setState(() { 
    isLoading = false;
    jokeText = result;
  });
}

// Inside the build method:
isLoading ? CircularProgressIndicator() : Text(jokeText);

8. Visual Learning: The HTTP Lifecycle

txt
12345
[ Flutter App ] --(GET request)--> [ Internet ] --(GET request)--> [ Server DB ]
                                                                       |
[ Flutter App ] <--(JSON String)-- [ Internet ] <--(JSON String)-- [ Server DB ]
      |
(setState draws the text on screen!)

9. Common Mistakes

  • Forgetting await: If you write final response = http.get(url); without the await keyword, Dart immediately moves to the next line of code before the server responds. response will be an empty object, your statusCode check will fail, and your app will crash. ALWAYS await network calls!
  • Missing Android Permissions: By default, Android blocks apps from accessing the internet! You MUST go into android/app/src/main/AndroidManifest.xml and add <uses-permission android:name="android.permission.INTERNET" />.

10. Best Practices

  • Try/Catch Blocks: The internet is inherently unstable. Users go into tunnels or lose Wi-Fi. Always wrap your HTTP requests inside a try/catch block. If the internet fails, the catch block fires, allowing you to show a friendly "Please check your connection" popup instead of the app freezing.

11. Practice Exercises

  1. 1. What Dart keyword is used to pause the execution of a function until a network request finishes, without freezing the visual UI?
  1. 2. What HTTP status code signifies a successful GET request response?

12. MCQs with Answers

Question 1

In Flutter, to make a secure network request to a REST API to fetch an article, which combination of method and package is standard?

Question 2

An HTTP POST request differs from a GET request primarily because:

13. Interview Questions

  • Q: Explain the purpose of async and await in Dart. Why is asynchronous programming mandatory for network operations on mobile devices?
  • Q: Walk me through the lifecycle of an HTTP GET request in Flutter. Include URL parsing, the request execution, status code validation, and error handling.
  • Q: What is the primary difference between a 200 status code and a 404 status code returned by an HTTP response? How should the UI reflect a 404 error?

14. FAQs

Q: My http.get returns a massive block of unreadable text. How do I extract just the "title" from it? A: APIs return data in a string format called JSON (JavaScript Object Notation). To extract specific pieces of data, you must decode the string into Dart Objects. We will cover this exactly in the next chapter!

15. Summary

In Chapter 18, our app connected to the world. We embraced Asynchronous Programming, utilizing Future, async, and await to process delays without freezing the UI. We installed the http package, executing GET requests to retrieve external data and POST requests to send form data. We validated server health using Status Codes (like 200 OK), handled connection errors gracefully via try/catch, and dynamically reflected loading states in our UI using CircularProgressIndicator.

16. Next Chapter Recommendation

Our app can download the data, but right now it is just a giant, ugly string of text. We need to convert it into usable Dart data. Proceed to Chapter 19: JSON Parsing in Flutter.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·