net_kit 4.4.5-dev
net_kit: ^4.4.5-dev 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
- π Parsing responses into models or lists of models using
INetKitModel
- π§ͺ Configurable base URLs for development and production
- π Internationalization support for error messages
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 {}
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
);
Sending requests #
Request a Single Model
Future<RandomUserModel> getRandomUser() async {
try {
final result = await netKitManager.requestModel<RandomUserModel>(
path: '/api',
method: RequestMethod.get,
model: const RandomUserModel(),
);
return result;
}
/// Catch the ApiException and handle it
on ApiException catch (e) {
/// Handle the error: example is to throw the error
throw Exception(e.message);
}
}
Request a List of Models
Future<List<ProductModel>> getProducts() async {
try {
final result = await netKitManager.requestList<ProductModel>(
path: '/products',
method: RequestMethod.get,
model: const ProductModel(),
);
return result;
}
/// Catch the ApiException and handle it
on ApiException catch (e) {
/// Handle the error: example is to throw the error
throw Exception(e.message);
}
}
Send a void Request
Future<void> deleteProduct() async {
try {
await netKitManager.requestVoid(
path: '/products',
method: RequestMethod.delete,
);
return;
}
/// Catch the ApiException and handle it
on ApiException catch (e) {
/// Handle the error: example is to throw the error
throw Exception(e.message);
}
}
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. These
tokens 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();
}
This method ensures that the tokens are removed from the headers, effectively logging out the user.
Refresh Token #
The NetKitManager provides a built-in mechanism for handling token refresh. This feature ensures that your access tokens are automatically refreshed when they expire, allowing for seamless and uninterrupted API requests.
Refresh Token Initialization #
To use the refresh token feature, you need to initialize the NetKitManager with the following parameters:
refreshTokenPath
: The API endpoint used to refresh the tokens.onTokenRefreshed
: A callback function that is called when the tokens are successfully refreshed.
Refresh Token Example #
final netKitManager = NetKitManager(
baseUrl: 'https://api.<URL>.com',
devBaseUrl: 'https://dev.<URL>.com',
loggerEnabled: true,
testMode: true,
refreshTokenPath: '/auth/refresh-token',
onTokenRefreshed: (authToken) async {
/// Save the new access token to the storage
},
// ... other parameters
);
How refresh token works #
The refresh token mechanism in NetKitManager
ensures that your access tokens are automatically
refreshed when they expire, allowing for seamless and uninterrupted API requests. Hereβs how it
works:
Token Expiry Detection:
- When an API request fails due to an expired access token, the
NetKitManager
detects this failure(401 status code) and automatically triggers the refresh token process.
Token Refresh Request:
- The NetKitManager automatically sends a request to the refreshTokenPath endpoint to obtain new access and refresh tokens.
Updating Tokens:
- Upon receiving new tokens, NetKitManager updates headers with the new access token.
- The onTokenRefreshed callback is called with new tokens, allowing you to store them securely.
Retrying the Original Request:
- The original API request that failed due to token expiry is retried with the new access token.
This process ensures that your application can continue to make authenticated requests without requiring user intervention when tokens expire.
π Standards Compliance #
NetKit
is built with security and interoperability in mind, and follows the official
specifications for modern API authentication:
π RFC Standards #
RFC | Description | Link |
---|---|---|
RFC 6749 | OAuth 2.0 Authorization Framework | Defines how clients securely obtain and use access & refresh tokens |
RFC 6750 | Bearer Token Usage | Specifies how to transmit access tokens in HTTP requests |
RFC 7519 | JSON Web Token (JWT) | Structure and use of signed tokens (used if JWTs are supported) |
π£ Help Us Stay Compliant #
If you find any behavior in NetKit that appears to be non-compliant with any of the above RFCs, please open an issue with a clear reference to the relevant RFC and section.
Weβre committed to improving and welcome community-driven compliance insights!
Migration Guidance #
β‘οΈ For detailed upgrade steps and breaking changes, see the full Migration Guide.
Planned Enhancements #
Feature | Status |
---|---|
Internationalization support for error messages | β |
No internet connection handling | β |
Provide basic example | β |
Provide more examples and use cases in the documentation | β |
MultiPartFile upload support | β |
Refresh Token implementation | β |
Enhance logging capabilities with customizable log levels | β |
Implement retry logic for failed requests | π‘ |
Add more tests to ensure the package is robust and reliable | β |
Authentication Feature | β |
Add Clean Architecture example | π‘ |
Contributing #
Contributions are welcome! Please open an issue or submit a pull request.
License #
This project is licensed under the MIT License.