In this post, we’ll walk through the process of making HTTP requests in a Flutter app using the http package.
Making API Call In Flutter Application
Getting Started
In the modern mobile app , every application interacts with some form of web service.API calls are essential Whether it's retrieving user data, submitting a form, or syncing with a server . Flutter, Google’s UI toolkit for building natively compiled apps, provides a clean way to handle API requests using Dart programming.
To make HTTP API calls in Flutter, the most commonly used package is http
. It is a client-side library that allows your Flutter app to perform HTTP operations and handle responses.
- Add the HTTP Package
- Import the Package
Add the HTTP Package
Add the http package to yourpubspec.yaml
:
dependencies:
flutter:
sdk: flutter
http: ^0.14.0
Then run:
flutter pub get
Import the Package
import 'package:http/http.dart' as http;
import 'dart:convert';
Example of Flutter API Call
GET Request Future<void> fetchData() async {
final url = Uri.parse('https://xyz.com/posts/1');
try {
final response = await http.get(url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print('Title: ${data['title']}');
} else {
print('Failed to load data: ${response.statusCode}');
}
} catch (e) {
print('Error: $e');
}
}
POST Request
Future<void> createPost() async {
final url = Uri.parse('https://xyz.com/posts');
final response = await http.post(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'title': 'foo',
'body': 'bar',
'userId': 1,
}),
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
print('Created Post: ${data['id']}');
} else {
print('Failed to create post');
}
}
Request With Bearer Token
Future<void> fetchProtectedData() async {
final url = Uri.parse('https://xyz.com/posts/1');
final token = 'your_api_token_here';
final response = await http.get(
url,
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
);
if (response.statusCode == 200) {
print('Data: ${json.decode(response.body)}');
} else {
print('Unauthorized or error');
}
}
Summary
Making API calls in Flutter is straightforward with the http
package. You can fetch data, send requests, and manage network responses effectively. As your app scales, consider using more advanced solutions like Dio, Chopper, or Retrofit, especially for caching, interceptors, and cleaner architecture.
Thanks