cyber_req 1.0.0
cyber_req: ^1.0.0 copied to clipboard
A flexible API client for Laravel backends with dynamic headers, bearer token support, and callbacks.
cyber_req #
A Robust and Customizable HTTP Client for Dart and Flutter #
cyber_req is a lightweight and flexible HTTP client designed to simplify network requests in your Dart and Flutter applications. Built on top of the http package, it provides a clean, intuitive API with powerful features like base URL configuration, custom headers, and integrated error handling, making your API interactions more efficient and reliable.
Features #
- Simple and Intuitive API: Easy-to-use methods for common HTTP verbs (GET, POST, PUT, DELETE).
- Base URL Configuration: Define a base URL once and make requests to relative paths.
- Customizable Headers: Set default headers for all requests or override them for specific calls.
- Integrated Error Handling: Automatic parsing of API errors and dedicated exception types (
ApiException,UnauthorizedException). - Bearer Token Support: Easily include bearer tokens for authenticated requests.
- Success and Failure Callbacks: Handle responses and errors gracefully with optional callbacks.
- Flexible Query Parameters: Pass query parameters as a Dart
Mapobject forGETrequests.
Installation #
Add cyber_req to your project by modifying your pubspec.yaml file:
dependencies:
cyber_req: ^1.0.0 # Use the latest version
After adding the dependency, run flutter pub get (for Flutter projects) or dart pub get (for pure Dart projects) to fetch the package.
Usage #
Basic Setup #
Initialize CyberReq with your API's base URL and any default headers:
import 'package:cyber_req/cyber_req.dart';
final cyberReq = CyberReq(
baseUrl: 'https://api.example.com/v1',
headers: {
'Content-Type': 'application/json',
'X-Custom-Header': 'Value',
},
// Optional: Handle unauthorized responses globally
onUnauthorized: () async {
print('User is unauthorized. Redirecting to login...');
// e.g., navigate to login screen, refresh token
},
);
Making GET Requests #
Fetch data from an endpoint. You can pass query parameters as a Map<String, dynamic>:
void fetchUsers() async {
try {
final response = await cyberReq.get(
'/users',
queryParams: {
'page': 1,
'limit': 10,
'status': 'active',
},
);
print('Users: ${response.body}');
} on ApiException catch (e) {
print('Error fetching users: ${e.message} (Status: ${e.statusCode})');
} on UnauthorizedException {
print('Access denied. Please log in again.');
} catch (e) {
print('An unexpected error occurred: $e');
}
}
Making POST Requests #
Send data to an endpoint. The data parameter accepts a Map<String, dynamic> which will be JSON-encoded:
void createUser() async {
try {
final newUser = {
'name': 'John Doe',
'email': 'john.doe@example.com',
};
final response = await cyberReq.post('/users', data: newUser);
print('User created: ${response.body}');
} on ApiException catch (e) {
print('Error creating user: ${e.message}');
}
}
Making PUT Requests #
Update resources on the server:
void updateUser(String userId) async {
try {
final updatedData = {
'email': 'john.doe.new@example.com',
};
final response = await cyberReq.put('/users/$userId', data: updatedData);
print('User updated: ${response.body}');
} on ApiException catch (e) {
print('Error updating user: ${e.message}');
}
}
Making DELETE Requests #
Remove resources from the server:
void deleteUser(String userId) async {
try {
final response = await cyberReq.delete('/users/$userId');
print('User deleted successfully.');
} on ApiException catch (e) {
print('Error deleting user: ${e.message}');
}
}
Handling Responses with Callbacks #
For more granular control, you can use onSuccess and onFailure callbacks:
void fetchDataWithCallbacks() {
cyberReq.get(
'/data',
onSuccess: (data) {
print('Data fetched successfully: $data');
},
onFailure: (error) {
print('Failed to fetch data: ${error.message}');
},
);
}
Using Bearer Tokens #
Pass a bearer token for authenticated requests. This can be set globally during initialization or per-request:
// Global token
final authenticatedReq = CyberReq(
baseUrl: 'https://api.example.com/v1',
bearerToken: 'your_global_auth_token',
);
// Per-request token (overrides global if both are set)
authenticatedReq.get(
'/protected-data',
bearerToken: 'your_specific_request_token',
);
API Reference #
CyberReq Class #
The primary class for interacting with your API.
Constructor
CyberReq({ required String baseUrl, String? bearerToken, http.Client? httpClient, UnauthorizedHandler? onUnauthorized, Map<String, String>? headers, })
baseUrl(requiredString): The base URL for all API requests.bearerToken(String?): An optional bearer token to be included in theAuthorizationheader for all requests made with this instance.httpClient(http.Client?): An optional customhttp.Clientinstance. Useful for testing or advanced configurations.onUnauthorized(UnauthorizedHandler?): An optional callbackFuture<void> Function()that is invoked when a401 Unauthorizedresponse is received. Ideal for global token refresh logic or redirecting to a login screen.headers(Map<String, String>?): Optional default headers to be sent with all requests.
Methods
-
Future<Map<String, dynamic>> get(String endpoint, {Map<String, dynamic>? queryParams, Map<String, String>? extraHeaders, String? bearerToken, SuccessCallback? onSuccess, FailureCallback? onFailure, List<int>? allowedStatusCodes})Makes aGETrequest.endpoint(String): The API endpoint relative to thebaseUrl.queryParams(Map<String, dynamic>?): Optional map of query parameters. Keys and values will be URL-encoded.extraHeaders(Map<String, String>?): Optional headers specific to this request, overriding default headers if conflicts exist.bearerToken(String?): Optional bearer token for this specific request.onSuccess(SuccessCallback?): Callback invoked on successful response (2xxstatus code).onFailure(FailureCallback?): Callback invoked on API error (4xxor5xxstatus code, or network error).allowedStatusCodes(List<int>?): Optional list of additional status codes (e.g.,201,204) that should be considered successful, even if they are not in the 2xx range.
-
Future<Map<String, dynamic>> post(String endpoint, {Map<String, dynamic>? data, Map<String, String>? extraHeaders, String? bearerToken, SuccessCallback? onSuccess, FailureCallback? onFailure, List<int>? allowedStatusCodes})Makes aPOSTrequest.endpoint(String): The API endpoint.data(Map<String, dynamic>?): The request body, which will be JSON-encoded.- (Other parameters are similar to
getmethod)
-
Future<Map<String, dynamic>> put(String endpoint, {Map<String, dynamic>? data, Map<String, String>? extraHeaders, String? bearerToken, SuccessCallback? onSuccess, FailureCallback? onFailure, List<int>? allowedStatusCodes})Makes aPUTrequest.endpoint(String): The API endpoint.data(Map<String, dynamic>?): The request body, which will be JSON-encoded.- (Other parameters are similar to
getmethod)
-
Future<Map<String, dynamic>> delete(String endpoint, {Map<String, String>? extraHeaders, String? bearerToken, SuccessCallback? onSuccess, FailureCallback? onFailure, List<int>? allowedStatusCodes})Makes aDELETErequest.endpoint(String): The API endpoint.- (Other parameters are similar to
getmethod)
Exceptions #
cyber_req throws specific exceptions to help you handle different error scenarios.
-
ApiExceptionThrown for general API errors (e.g.,4xx,5xxstatus codes, network issues).message(String): A descriptive error message.statusCode(int?): The HTTP status code, if available.
-
UnauthorizedExceptionA specializedApiExceptionthrown specifically when a401 Unauthorizedstatus code is received.
Contributing #
We welcome contributions to cyber_req! If you have a bug report, feature request, or want to contribute code, please feel free to open an issue or submit a pull request on the GitHub repository. (Replace with your actual GitHub link)
License #
This project is licensed under the custom license. See the LICENSE file for details.