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 officialhttp 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
httppackage frompub.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.
Add the package to
pubspec.yaml:
http: ^1.1.0
- 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
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 abody (the data) along with the request.
dart
7. Integrating with the UI
How do we show the joke on the screen when it arrives? While there is a specialized widget calledFutureBuilder, beginners should use setState()!
dart
8. Visual Learning: The HTTP Lifecycle
txt
9. Common Mistakes
-
Forgetting
await: If you writefinal response = http.get(url);without theawaitkeyword, Dart immediately moves to the next line of code before the server responds.responsewill be an empty object, yourstatusCodecheck will fail, and your app will crash. ALWAYSawaitnetwork calls!
-
Missing Android Permissions: By default, Android blocks apps from accessing the internet! You MUST go into
android/app/src/main/AndroidManifest.xmland 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/catchblock. If the internet fails, thecatchblock fires, allowing you to show a friendly "Please check your connection" popup instead of the app freezing.
11. Practice Exercises
- 1. What Dart keyword is used to pause the execution of a function until a network request finishes, without freezing the visual UI?
-
2.
What HTTP status code signifies a successful
GETrequest 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
asyncandawaitin 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
200status code and a404status code returned by an HTTP response? How should the UI reflect a404error?
14. FAQs
Q: Myhttp.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, utilizingFuture, 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.