Back to Articles

Intermediate

API Integration and HTTP Requests in Flutter

· 12 min read

Introduction

Most modern mobile applications communicate with server-side APIs to exchange data. There are several approaches to API integration in Flutter. In this article, we'll examine the most popular and reliable methods in detail.

The main topics to consider when integrating APIs are: HTTP requests (GET, POST, PUT, DELETE), JSON data parsing, error handling, loading states, and network error handling.

Installing the HTTP Package

The most popular package for making HTTP requests in Flutter is the `http` package. To add this package to your project, you need to add it to your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0
  provider: ^6.1.1

After adding the package, run `flutter pub get` to install it.

Basic HTTP Requests

With the HTTP package, you can make GET, POST, PUT, and DELETE requests. Let's start with a simple GET request:

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

class ApiService {
  // Define base URL
  static const String baseUrl = 'https://jsonplaceholder.typicode.com';
  
  // Make GET request
  Future<List<Map<String, dynamic>>> getPosts() async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/posts'),
        headers: {
          'Content-Type': 'application/json',
        },
      );
      
      // Check status code
      if (response.statusCode == 200) {
        // Parse JSON
        final List<dynamic> data = json.decode(response.body);
        return data.cast<Map<String, dynamic>>();
      } else {
        throw Exception('Failed to load posts: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Network error: $e');
    }
  }
  
  // Make POST request
  Future<Map<String, dynamic>> createPost({
    required String title,
    required String body,
    required int userId,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl/posts'),
        headers: {
          'Content-Type': 'application/json',
        },
        body: json.encode({
          'title': title,
          'body': body,
          'userId': userId,
        }),
      );
      
      if (response.statusCode == 201) {
        return json.decode(response.body) as Map<String, dynamic>;
      } else {
        throw Exception('Failed to create post: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Network error: $e');
    }
  }
}

In the code above, we created a basic API service class. This class can make GET and POST requests. We use try-catch blocks for error handling for each request.

Creating Model Classes

Creating model classes to better manage data coming from the API is important. This provides type safety and improves code readability.

class Post {
  final int id;
  final int userId;
  final String title;
  final String body;
  
  Post({
    required this.id,
    required this.userId,
    required this.title,
    required this.body,
  });
  
  // Create Post object from JSON
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'] as int,
      userId: json['userId'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }
  
  // Convert Post object to JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'userId': userId,
      'title': title,
      'body': body,
    };
  }
  
  @override
  String toString() {
    return 'Post(id: $id, userId: $userId, title: $title)';
  }
}

With the model class, we can use raw JSON data from the API in a type-safe way. The `fromJson` factory constructor creates an object from JSON, while the `toJson` method converts the object to JSON.

State Management with Provider

Using state management to manage API calls and update the UI is important. Let's see how to do this with the Provider package:

import 'package:flutter/foundation.dart';
import '../models/post.dart';
import '../services/api_service.dart';

class PostProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  
  List<Post> _posts = [];
  bool _isLoading = false;
  String? _error;
  
  // Getters
  List<Post> get posts => _posts;
  bool get isLoading => _isLoading;
  String? get error => _error;
  
  // Load posts
  Future<void> loadPosts() async {
    _isLoading = true;
    _error = null;
    notifyListeners();
    
    try {
      final data = await _apiService.getPosts();
      _posts = data.map((json) => Post.fromJson(json)).toList();
      _error = null;
    } catch (e) {
      _error = e.toString();
      _posts = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
  
  // Create new post
  Future<bool> createPost({
    required String title,
    required String body,
    required int userId,
  }) async {
    _isLoading = true;
    _error = null;
    notifyListeners();
    
    try {
      final data = await _apiService.createPost(
        title: title,
        body: body,
        userId: userId,
      );
      
      // Add new post to list
      final newPost = Post.fromJson(data);
      _posts.insert(0, newPost);
      _error = null;
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = e.toString();
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }
  
  // Clear posts
  void clearPosts() {
    _posts = [];
    notifyListeners();
  }
}

The Provider class manages API calls and updates the UI. Thanks to the `ChangeNotifier` mixin, it notifies all listeners when the state changes. We can show loading and error states to the user with `isLoading` and `error` states.

UI Implementation

Now let's create a UI using the Provider. This UI will list posts and allow adding new posts:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/post_provider.dart';
import '../models/post.dart';

class PostsScreen extends StatefulWidget {
  const PostsScreen({super.key});

  @override
  State<PostsScreen> createState() => _PostsScreenState();
}

class _PostsScreenState extends State<PostsScreen> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _bodyController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    // Load posts when page opens
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<PostProvider>().loadPosts();
    });
  }
  
  @override
  void dispose() {
    _titleController.dispose();
    _bodyController.dispose();
    super.dispose();
  }
  
  Future<void> _showAddPostDialog() async {
    return showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Add New Post'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _titleController,
              decoration: const InputDecoration(
                labelText: 'Title',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _bodyController,
              decoration: const InputDecoration(
                labelText: 'Content',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () async {
              final provider = context.read<PostProvider>();
              final success = await provider.createPost(
                title: _titleController.text,
                body: _bodyController.text,
                userId: 1,
              );
              
              if (success && mounted) {
                Navigator.pop(context);
                _titleController.clear();
                _bodyController.clear();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Post added successfully!')),
                );
              } else if (mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Error: ${provider.error}')),
                );
              }
            },
            child: const Text('Add'),
          ),
        ],
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Posts'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              context.read<PostProvider>().loadPosts();
            },
          ),
        ],
      ),
      body: Consumer<PostProvider>(
        builder: (context, provider, child) {
          // Loading state
          if (provider.isLoading && provider.posts.isEmpty) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          
          // Error state
          if (provider.error != null && provider.posts.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.error_outline,
                    size: 64,
                    color: Colors.red,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    'Error: ${provider.error}',
                    style: const TextStyle(color: Colors.red),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => provider.loadPosts(),
                    child: const Text('Retry'),
                  ),
                ],
              ),
            );
          }
          
          // Post list
          if (provider.posts.isEmpty) {
            return const Center(
              child: Text('No posts yet'),
            );
          }
          
          return RefreshIndicator(
            onRefresh: () => provider.loadPosts(),
            child: ListView.builder(
              itemCount: provider.posts.length,
              padding: const EdgeInsets.all(8),
              itemBuilder: (context, index) {
                final post = provider.posts[index];
                return Card(
                  margin: const EdgeInsets.symmetric(vertical: 4),
                  child: ListTile(
                    title: Text(
                      post.title,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                    subtitle: Text(
                      post.body,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    trailing: Text(
                      'ID: ${post.id}',
                      style: const TextStyle(fontSize: 12),
                    ),
                    onTap: () {
                      // Navigate to post detail page
                    },
                  ),
                );
              },
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showAddPostDialog,
        child: const Icon(Icons.add),
      ),
    );
  }
}

This screen updates the UI using the state from the Provider. Thanks to the `Consumer` widget, it automatically rebuilds when the state in the Provider changes. It shows loading, error, and success states to the user.

Error Handling and Retry Mechanism

Error handling is very important in network operations. Internet connection may be lost, server may return errors, or timeouts may occur. Let's create an advanced error handling mechanism to handle these situations:

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

class ApiException implements Exception {
  final String message;
  final int? statusCode;
  
  ApiException(this.message, [this.statusCode]);
  
  @override
  String toString() => message;
}

class ErrorHandler {
  static ApiException handleError(dynamic error) {
    if (error is http.ClientException) {
      return ApiException('No internet connection. Please check your connection.');
    }
    
    if (error is http.Response) {
      switch (error.statusCode) {
        case 400:
          return ApiException('Invalid request', 400);
        case 401:
          return ApiException('Authorization error', 401);
        case 403:
          return ApiException('Access denied', 403);
        case 404:
          return ApiException('Resource not found', 404);
        case 500:
          return ApiException('Server error', 500);
        default:
          return ApiException('Unknown error: ${error.statusCode}', error.statusCode);
      }
    }
    
    return ApiException('Unexpected error: $error');
  }
  
  static String getErrorMessage(dynamic error) {
    if (error is ApiException) {
      return error.message;
    }
    return 'An error occurred: $error';
  }
}

The error handler class catches different error types and returns user-friendly messages. This allows showing more understandable error messages to users.

Interceptor and Base URL Management

For a more professional approach, it's useful to manage HTTP requests from a central location and add interceptors. This can be used to add authentication tokens, perform logging, and manage the base URL:

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

class HttpClient {
  final String baseUrl;
  final Map<String, String> defaultHeaders;
  
  HttpClient({
    required this.baseUrl,
    Map<String, String>? headers,
  }) : defaultHeaders = headers ?? {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        };
  
  // Add token
  void setAuthToken(String token) {
    defaultHeaders['Authorization'] = 'Bearer $token';
  }
  
  // Remove token
  void removeAuthToken() {
    defaultHeaders.remove('Authorization');
  }
  
  // GET request
  Future<http.Response> get(
    String endpoint, {
    Map<String, String>? headers,
    Map<String, dynamic>? queryParameters,
  }) async {
    try {
      var uri = Uri.parse('$baseUrl$endpoint');
      
      // Add query parameters
      if (queryParameters != null) {
        uri = uri.replace(queryParameters: queryParameters.map(
          (key, value) => MapEntry(key, value.toString()),
        ));
      }
      
      final response = await http.get(
        uri,
        headers: {...defaultHeaders, ...?headers},
      ).timeout(
        const Duration(seconds: 30),
        onTimeout: () {
          throw ApiException('Request timed out');
        },
      );
      
      _handleResponse(response);
      return response;
    } catch (e) {
      throw ErrorHandler.handleError(e);
    }
  }
  
  // POST request
  Future<http.Response> post(
    String endpoint, {
    Map<String, String>? headers,
    Object? body,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl$endpoint'),
        headers: {...defaultHeaders, ...?headers},
        body: body is String ? body : json.encode(body),
      ).timeout(
        const Duration(seconds: 30),
        onTimeout: () {
          throw ApiException('Request timed out');
        },
      );
      
      _handleResponse(response);
      return response;
    } catch (e) {
      throw ErrorHandler.handleError(e);
    }
  }
  
  // Response check
  void _handleResponse(http.Response response) {
    if (response.statusCode >= 400) {
      throw ErrorHandler.handleError(response);
    }
  }
}

This HttpClient class manages all HTTP requests from a central location. It automatically adds authentication tokens, handles timeouts, and manages errors.

Caching and Offline Support

We can add a caching mechanism so the app can work offline. This stores previously loaded data and displays it when there's no internet connection:

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CacheService {
  static const String _cachePrefix = 'api_cache_';
  static const Duration defaultCacheDuration = Duration(hours: 1);
  
  // Cache data
  static Future<void> cacheData(
    String key,
    dynamic data, {
    Duration? duration,
  }) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final cacheData = {
        'data': data,
        'timestamp': DateTime.now().millisecondsSinceEpoch,
        'expiresAt': DateTime.now()
            .add(duration ?? defaultCacheDuration)
            .millisecondsSinceEpoch,
      };
      
      await prefs.setString(
        '$_cachePrefix$key',
        json.encode(cacheData),
      );
    } catch (e) {
      debugPrint('Cache error: $e');
    }
  }
  
  // Get cached data
  static Future<dynamic> getCachedData(String key) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final cachedString = prefs.getString('$_cachePrefix$key');
      
      if (cachedString == null) return null;
      
      final cacheData = json.decode(cachedString) as Map<String, dynamic>;
      final expiresAt = cacheData['expiresAt'] as int;
      
      // Check if cache expired
      if (DateTime.now().millisecondsSinceEpoch > expiresAt) {
        await prefs.remove('$_cachePrefix$key');
        return null;
      }
      
      return cacheData['data'];
    } catch (e) {
      debugPrint('Cache read error: $e');
      return null;
    }
  }
  
  // Clear cache
  static Future<void> clearCache(String? key) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      if (key != null) {
        await prefs.remove('$_cachePrefix$key');
      } else {
        // Clear all cache
        final keys = prefs.getKeys();
        for (final k in keys) {
          if (k.startsWith(_cachePrefix)) {
            await prefs.remove(k);
          }
        }
      }
    } catch (e) {
      debugPrint('Cache clear error: $e');
    }
  }
}

The cache service stores data on the device using SharedPreferences. This allows displaying previously loaded data even when the app is offline.

Best Practices and Recommendations

1. Environment Variables

It's important to store API URLs and other configurations as environment variables. This allows easy switching between development and production environments.

class AppConfig {
  static const String apiBaseUrl = String.fromEnvironment(
    'API_BASE_URL',
    defaultValue: 'https://api.example.com',
  );
  
  static const bool isProduction = bool.fromEnvironment('dart.vm.product');
  
  static String get apiUrl => isProduction 
    ? 'https://api.production.com'
    : 'https://api.staging.com';
}

2. Retry Mechanism

Adding an automatic retry mechanism for network errors improves user experience. It's especially useful for temporary network issues.

import 'dart:async';
import 'dart:math';

class RetryHelper {
  static Future<T> retry<T>({
    required Future<T> Function() action,
    int maxRetries = 3,
    Duration delay = const Duration(seconds: 1),
  }) async {
    int attempt = 0;
    
    while (attempt < maxRetries) {
      try {
        return await action();
      } catch (e) {
        attempt++;
        if (attempt >= maxRetries) {
          rethrow;
        }
        
        // Exponential backoff
        final waitTime = delay * pow(2, attempt - 1);
        await Future.delayed(waitTime);
      }
    }
    
    throw Exception('Max retries reached');
  }
}

3. Loading States

It's important to always show loading states to users. This indicates that the app is working and data is being loaded.

Conclusion

API integration in Flutter is quite easy with the right tools and approaches. What we learned in this article:

• You can make GET, POST, PUT, DELETE requests with the HTTP package • You can do type-safe data management with model classes • You can do state management with Provider • You can add error handling and retry mechanisms • You can provide offline support with caching

By using these structures, you can create reliable and user-friendly API integrations. Remember that each project has different needs, so you may need to customize these structures according to your project.

Additional Resources

For more information, you can check these resources:

• Flutter HTTP Package: https://pub.dev/packages/http • Provider Package: https://pub.dev/packages/provider • JSON Serialization: https://flutter.dev/docs/development/data-and-backend/json