advanced_api_client 1.0.2 copy "advanced_api_client: ^1.0.2" to clipboard
advanced_api_client: ^1.0.2 copied to clipboard

Production-ready Flutter/Dart API client built on Dio with authentication, automatic token refresh, retry interceptor, file uploads, global error handling, and clean architecture.

Advanced API Client #

A powerful, production-ready Flutter/Dart HTTP client built on top of dio.

advanced_api_client simplifies REST API integration with built-in:

  • Authentication handling
  • Automatic token refresh
  • Retry mechanism
  • File uploads
  • Pagination support
  • Global error handling
  • Custom interceptors
  • Session termination
  • Request deduplication
  • Rate limiting
  • Clean architecture

Designed for scalability and real-world production apps.


๐Ÿš€ API Client Architecture #

AdvancedApiClient
โ”œโ”€โ”€ RetryInterceptor
โ”œโ”€โ”€ AuthInterceptor
โ”‚    โ”œโ”€โ”€ Token attach
โ”‚    โ”œโ”€โ”€ Queue requests
โ”‚    โ”œโ”€โ”€ Refresh lock
โ”‚    โ”œโ”€โ”€ Retry failed calls
โ”‚    โ””โ”€โ”€ Prevent multiple redirects
โ”œโ”€โ”€ Upload cancel tokens
โ”œโ”€โ”€ Request deduplication
โ”œโ”€โ”€ Rate limiting
โ”œโ”€โ”€ Global cancel
โ””โ”€โ”€ SSL bypass (dev)

โœจ Features #

  • โœ… GET, POST, PUT, PATCH, DELETE
  • ๐Ÿ” Token-based authentication
  • ๐Ÿ”„ Automatic token refresh (401 handling)
  • โ™ป๏ธ Retry interceptor (connection errors + timeout support)
  • ๐Ÿ“ค Single & multiple file uploads
  • ๐Ÿ“ฆ Pagination-ready
  • ๐Ÿงฉ Custom interceptor support
  • ๐Ÿ›‘ Global error callback
  • ๐Ÿšช Session termination support
  • ๐Ÿงช Works with Flutter & pure Dart
  • ๐Ÿ†• Dynamic refresh token bodyBuilder
  • ๐Ÿ›ก Safe retry after token refresh for file uploads
  • ๐Ÿ“‘ Global header support
  • โšก Request deduplication support -๐Ÿšฆ Rate limiting support

๐Ÿ“ฆ Installation #

Add this to your pubspec.yaml:

dependencies:
  advanced_api_client: ^1.0.2

Then run:

flutter pub get

๐Ÿš€ Getting Started #

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await AdvancedApiClient.initialize(
    config: ApiConfig(
      baseUrl: "https://api.example.com",
      enableAutoRefresh: true, // false to call onSessionExpired
      onSessionExpired: () {
        debugPrint("Session expired. Please login again");
        final navigator = navigatorKey.currentState;

        if (navigator == null) return;

        // Navigate to login
        navigator.pushNamedAndRemoveUntil(
          "/login",
              (route) => false,
        );

        // Show snackbar
        ScaffoldMessenger.of(navigator.context).showSnackBar(
          const SnackBar(
            content: Text("Session expired. Please login again."),
          ),
        );
      },
      refreshConfig: RefreshConfig(
        path: "/auth/refresh",
        method: "POST",
        // Use bodyBuilder for dynamic runtime body
        bodyBuilder: () async {
          final prefs = await SharedPreferences.getInstance();
          final userId = prefs.getString("user_id") ?? "";
          return {"user_id": userId, "from_source": 1};
        },
        // or use body for static data
        body: {
          "from_source": 1
        },
        tokenParser: (data) => data["access_token"],
        headers: {
          "App-Version": "1.0.0",
          "Platform": "Flutter",
        },
      ),
    ),
  );

  runApp(MyApp());
}

Access anywhere:

final client = AdvancedApiClient.instance;

2๏ธโƒฃ Lazy Initialization (Optional) #

final client = await AdvancedApiClient.getInstance();

โš™๏ธ ApiConfig #

The ApiConfig class allows you to configure the API client behavior.

class ApiConfig {
  final String baseUrl;
  final bool enableAutoRefresh;
  final void Function()? onSessionExpired;
  final RefreshConfig? refreshConfig;
  final List<Interceptor>? interceptors;
  final void Function(DioException e, RequestOptions request)? onError;
  final bool enableLogs;
  final Map<String, dynamic>? headers;
  final bool allowBadCertificates;

  const ApiConfig({
    required this.baseUrl,
    this.enableAutoRefresh = true,
    this.onSessionExpired,
    this.refreshConfig,
    this.interceptors,
    this.onError,
    this.enableLogs = true,
    this.headers,
    this.allowBadCertificates = false,
  });
}

๐Ÿ”น baseUrl (Required) #

Base URL of your API.

ApiConfig(
  baseUrl: "https://api.example.com",
);

๐Ÿ”น refreshConfig (Optional) #

Used to automatically refresh access tokens when a 401 response is received.

Example:

ApiConfig(
  baseUrl: "https://api.example.com",
  refreshConfig: RefreshConfig(
    path: "/auth/refresh",
    method: "POST",
    // Dynamic runtime body
    bodyBuilder: () async {
    final prefs = await SharedPreferences.getInstance();
    final userId = prefs.getString("user_id") ?? "";
    return {"user_id": userId, "from_source": 1};
    },
    // Static body
    body: {"from_source": 1}
    tokenParser: (data) => data["access_token"],
  ),
);

๐Ÿ”น interceptors (Optional) #

Add custom dio interceptors.

ApiConfig(
  baseUrl: "https://api.example.com",
  interceptors: [
    LogInterceptor(responseBody: true),
  ],
);

๐Ÿ”น onError (Optional) #

Global error callback triggered for all request errors.

ApiConfig(
  baseUrl: "https://api.example.com",
  onError: (DioException e, RequestOptions request) async {
    final statusCode = e.response?.statusCode;

    if (statusCode == 401) {
      await AdvancedApiClient.instance.terminateSession();
    }

    if (statusCode == 500) {
      debugPrint("Server error occurred");
    }

    if (e.type == DioExceptionType.connectionError) {
      debugPrint("No internet connection");
    }
  },
);

๐ŸŒ Basic Requests #

GET #

await client.get(
  endpoint: "/users",
  headers: {"X-Custom-Header": "12345"},
  rateLimit: Duration(seconds: 2),
);

POST #

await client.post(
  endpoint: "/users",
  body: {"name": "John"},
  headers: {"X-Custom-Header": "12345"},
  rateLimit: Duration(seconds: 2),
);

PUT #

await client.put(
  endpoint: "/users/1",
  body: {"name": "Updated"},
  headers: {"X-Custom-Header": "12345"},
  rateLimit: Duration(seconds: 2),
);

PATCH #

await client.patch(
  endpoint: "/users/1",
  body: {"status": "active"},
  headers: {"X-Custom-Header": "12345"},
  rateLimit: Duration(seconds: 2),
);

DELETE #

await client.delete(
  endpoint: "/users/1",
  rateLimit: Duration(seconds: 2),
);

๐Ÿ“ค File Upload Examples #

final client = AdvancedApiClient.instance;

Upload Single File #

await client.upload(
  endpoint: "/common/file-upload/image",
  files: {
    "image": [pickedFile.path],
  },
  headers: {"X-Custom-Header": "12345"},
  rateLimit: Duration(seconds: 2),
);

Upload Multiple Files (Same Field) #

await client.upload(
  endpoint: "/common/file-upload/image",
  files: {
    "image": filePaths, // List<String>
  },
  headers: {"X-Custom-Header": "12345"},
  rateLimit: Duration(seconds: 2),
);

Upload Multiple Files (Different Fields) #

await client.upload(
  endpoint: "/upload",
  files: {
    "profile_image": [profilePath],
    "documents": documentPaths,
  },
  fields: {
    "user_id": 1,
    "type": "verification",
  },
  headers: {"X-Custom-Header": "12345"},
  rateLimit: Duration(seconds: 2),
);

๐Ÿšช Terminate Session #

Clears tokens and cancels all pending requests:

await AdvancedApiClient.instance.terminateSession();

๐Ÿ”„ Retry Mechanism #

Built-in retry interceptor supports:

  • Connection errors
  • Receive timeout
  • Configurable retry attempts
  • Optional exponential backoff

Helps reduce random network failures in production.


๐Ÿงช Works With #

  • Flutter Mobile
  • Flutter Web
  • Flutter Desktop
  • Pure Dart projects

๐Ÿ“ License #

MIT License ยฉ 2026


โค๏ธ Why Advanced API Client? #

Because production apps need more than just dio.

You get:

  • Cleaner codebase
  • Centralized API management
  • Safer authentication flow
  • Easier scaling
  • Better maintainability
0
likes
150
points
56
downloads

Documentation

Documentation
API reference

Publisher

unverified uploader

Weekly Downloads

Production-ready Flutter/Dart API client built on Dio with authentication, automatic token refresh, retry interceptor, file uploads, global error handling, and clean architecture.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

dio, flutter, shared_preferences

More

Packages that depend on advanced_api_client