Module 2
Topic 1

HTTP Requests

Making network requests in Flutter using the http package — the foundation of API integration.

http package on pub.dev Flutter Docs – Fetch Data
What Are HTTP Requests?

HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. In Flutter, HTTP requests are how your app talks to servers and exchanges data with APIs (Application Programming Interfaces).

When you make an HTTP request, you're essentially asking a server to:

  • GET — Retrieve data (e.g., fetch a list of users)
  • POST — Send new data (e.g., create a new user account)
  • PUT — Update existing data (e.g., edit a user profile)
  • DELETE — Remove data (e.g., delete a user account)

✅ The Big Idea

HTTP requests are how your Flutter app connects to the internet and fetches or sends data . Without them, your app would be isolated and unable to display dynamic content, user data, or interact with web services.

Common HTTP Methods

HTTP defines several methods (verbs) that indicate the desired action to be performed on a resource. Here are the most common ones you'll use in Flutter:

GET
Retrieve data from the server
POST
Send new data to the server
PUT
Update existing data (full replace)
PATCH
Partially update existing data
DELETE
Remove data from the server
The http Package

The http package is the official and most popular way to make HTTP requests in Flutter and Dart. It provides a simple, composable, and Future-based API for working with HTTP resources.

📦 Why the http Package?

  • Official – Maintained by the Dart team
  • Multi-platform – Works on mobile, desktop, and web
  • Simple API – Easy to use with top-level functions
  • Composable – Can be extended with custom clients
  • Testable – Supports mocking for unit tests
Setting Up the http Package

Before you can make HTTP requests, you need to add the http package to your project and configure your app's permissions.

⚠️ Important

Always check your platform permissions! Android requires the Internet permission, and macOS requires the network client entitlement. Without these, your HTTP requests will fail.

Making a GET Request

The most common HTTP request is GET , which retrieves data from a server. Here's how to make a GET request using the http package.

🔑 Key Points

  • Uri.parse() – Converts a string URL to a Uri object
  • headers – Optional headers like Accept or Authorization
  • Future – The request is asynchronous, so it returns a Future
  • response.statusCode – 200 means success, 404 means not found
  • response.body – The raw response data (usually JSON)
Handling HTTP Responses

When you make an HTTP request, the server responds with a status code and a body . You need to handle different scenarios:

⚠️ Common Status Codes

  • 200 – Success (OK)
  • 201 – Created (POST successful)
  • 400 – Bad Request (invalid data)
  • 401 – Unauthorized (need to log in)
  • 404 – Not Found (resource doesn't exist)
  • 500 – Internal Server Error (server problem)
Complete Example: Fetching an Album

Here's a complete example that fetches an album from the JSONPlaceholder API and displays it in a Flutter app. This follows the official Flutter cookbook recipe.

Step-by-Step Explanation
1.
Add the http package – Run flutter pub add http to add the dependency.
2.
Define the data model – Create an Album class with a fromJson factory constructor to parse JSON data.
3.
Create the fetch function fetchAlbum() makes a GET request, checks the status code, and parses the response into an Album object.
4.
Call the function in initState – Store the Future in a state variable and call it once when the widget is created.
5.
Display with FutureBuilder – Use FutureBuilder to handle loading, error, and data states automatically.
Testing HTTP Requests

For better testability, it's recommended to use a Client instance rather than the top-level functions like http.get() . This makes it easier to mock HTTP requests in your tests.

✅ Best Practice

Always use a Client instance for testability. Accept a Client parameter in your service classes and use it instead of the top-level functions. This allows you to inject mock clients in your tests.

Common Mistakes
❌ Mistake 1: Not handling status codes

Always check the statusCode before parsing the response. A 404 or 500 error will contain error information, not the data you expect.

✅ Correct: Always check status codes

Use if (response.statusCode == 200) before parsing, and throw exceptions for other status codes.

❌ Mistake 2: Forgetting platform permissions

Android needs the Internet permission, and macOS needs the network client entitlement. Without these, your requests will fail silently.

✅ Correct: Configure permissions

Add <uses-permission android:name="android.permission.INTERNET" /> to AndroidManifest.xml and the network client entitlement to your macOS files.

❌ Mistake 3: Making requests in build()

The build() method is called frequently. Making network requests inside it will cause unnecessary API calls and slow down your app.

✅ Correct: Make requests in initState()

Call your fetch function in initState() and store the Future in a state variable.

🎯 Key Takeaway

HTTP requests are the foundation of API integration in Flutter. The http package provides a simple, powerful way to make GET, POST, PUT, and DELETE requests. Always check status codes, handle errors, and use a Client for testability.