net_kit 5.3.0
net_kit: ^5.3.0 copied to clipboard
Netkit is a library that provides a set of tools to work with network requests.
Contents #
π½ Click to expand
Features #
- π Automatic token refresh with queue-safe retry
- βοΈ
onBeforeRefreshRequest
to mutate refresh payload - π Parsing responses into models or lists using
INetKitModel
- π§ͺ Configurable base URLs for development and production
- π Internationalization support for error messages
- π¦ Multipart upload support
- π Extensible logger integration
Sponsors #
A big thanks to our awesome sponsors for keeping this project going!οΈ Want to help out? Consider becoming a sponsor!
|
|
|
Getting started #
Initialize #
Initialize the NetKitManager with the parameters:
import 'package:net_kit/net_kit.dart';
final netKitManager = NetKitManager(
baseUrl: 'https://api.<URL>.com',
devBaseUrl: 'https://dev.<URL>.com',
// ... other parameters
);
Extend the model #
Requests such as: requestModel
andrequestList
require the model to
extend INetKitModel
in order to be used with the NetKitManager. By extending, INetKitModel
fromJson
and toJson
methods will be needed to be implemented, so the model can be serialized and
deserialized.
class TodoModel extends INetKitModel {}
Custom Void Models in Uploading #
β οΈ Custom Void Models: If you want to handle endpoints that return no data (i.e., void/empty responses) using your own model, your model must implement VoidModel from this package.
Example:
class AppVoidModel implements INetKitModel, VoidModel {
@override
Map<String, dynamic> toJson() => {};
@override
AppVoidModel fromJson(Map<String, dynamic> json) => AppVoidModel();
}
Without implementing VoidModel, void requests will not be recognized correctly and may throw exceptions.
Sending requests #
NetKitManager provides several methods for making HTTP requests. Each method is designed for specific use cases and response types.
Available Request Methods #
Method | Description | Use Case |
---|---|---|
requestModel |
Request a single model | Get a single resource |
requestList |
Request a list of models | Get multiple resources |
requestVoid |
Send a request without expecting data | Delete, update operations |
requestModelMeta |
Request a model with metadata | Get a resource with additional info |
requestListMeta |
Request a list with metadata | Get paginated data with metadata |
uploadMultipartData |
Upload a single file | File uploads |
uploadFormData |
Upload form data | Form submissions with files |
Request Examples #
- π Request a Single Model β
- π Request a List of Models β
- π Send a Void Request β
- π Request Model with Metadata β
- π Request List with Metadata (Pagination) β
- π Upload Multipart Data (Single File) β
- π Upload Form Data β
Why DataKey is Used #
Many APIs return responses in a wrapped format where the actual data is nested under a specific key. For example:
{
"success": true,
"data": {
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
"message": "User retrieved successfully"
}
Without DataKey configuration, you would need to manually extract the data from the data
field in every response. NetKit's DataKey feature automatically handles this extraction, making your code cleaner and more maintainable.
DataKey Configuration #
The useDataKey
parameter (default: true
) allows you to control whether to use the configured dataKey
wrapper for individual requests. This is useful when you have different API endpoints that return data in different formats.
- When
useDataKey: true
(default): Uses the configureddataKey
to extract data from the response - When
useDataKey: false
: Usesresponse.data
directly, ignoring thedataKey
configuration - Note: This parameter has no effect if
dataKey
is not set in the NetKitManager configuration
Available on all request methods: requestModel
, requestModelMeta
, requestList
, requestListMeta
, uploadMultipartData
, and uploadFormData
.
Advanced Examples #
For more detailed examples including pagination, error handling, and real-world use cases, see EXAMPLES.md.
Setting Tokens #
The NetKitManager allows you to set and manage access and refresh tokens, which are essential for authenticated API requests. Below are the methods provided to set, update, and remove tokens.
Setting Access and Refresh Tokens
To set the access and refresh tokens, use the setAccessToken
and setRefreshToken
methods. The
accessToken
token will be added to the headers of every request made by the NetKitManager.
Note: these should be set on every app launch or when the user logs in.
/// Your method to set the tokens
void setTokens(String accessToken, String refreshToken) {
netKitManager.setAccessToken(accessToken);
netKitManager.setRefreshToken(refreshToken);
}
User Logout #
When a user logs out, you should remove the access and refresh tokens using the removeAccessToken
and removeRefreshToken
methods.
Example:
/// Method to log out the user
void logoutUser() {
netKitManager.removeAccessToken();
netKitManager.removeRefreshToken();
}
Token Management #
NetKitManager provides comprehensive token management including automatic refresh, secure storage, and RFC-compliant authentication flows.
Quick Token Setup #
final netKitManager = NetKitManager(
baseUrl: 'https://api.example.com',
refreshTokenPath: '/auth/refresh-token',
onTokenRefreshed: (authToken) async {
await secureStorage.saveTokens(
accessToken: authToken.accessToken,
refreshToken: authToken.refreshToken,
);
},
);
Comprehensive Token Management #
For detailed token management documentation including:
- RFC Compliance (OAuth 2.0, Bearer Token, HTTP Authentication)
- Token Refresh Configuration with advanced options
- Secure Token Storage best practices
- Error Handling for token operations
- Security Considerations and best practices
π View Complete Token Management Guide β
Logger Integration #
The NetKitManager
uses a logger internally, for example, during the refresh token stages. To add
custom logging, you need to create a class that implements the INetKitLogger
interface. Below is
an example of how to create a NetworkLogger
class:
You can find the full example
of
NetworkLogger
here.
final netKitManager = NetKitManager(
baseUrl: 'https://api.<URL>.com',
logger: NetworkLogger(),
// ... other parameters
);
Migration Guidance #
β‘οΈ For detailed upgrade steps and breaking changes, see the full Migration Guide.
Feature Status #
Feature | Status |
---|---|
Internationalization support for error messages | β |
No internet connection handling | β |
Basic examples and documentation | β |
Comprehensive examples and use cases | β |
MultiPartFile upload support | β |
FormData upload support | β |
Refresh Token implementation (RFC 6749/6750 compliant) | β |
Customizable logging with log levels | β |
Request retry logic for failed requests | β |
Comprehensive test coverage | β |
Authentication and token management | β |
DataKey configuration with per-request override | β |
Pagination support with metadata | β |
Service layer pattern examples | β |
Repository pattern examples | β |
Error handling strategies | β |
File upload with wrapper patterns | β |
Token management documentation | β |
Contributing #
Contributions are welcome! Please open an issue or submit a pull request.
License #
This project is licensed under the MIT License.