cyber_req 1.0.1 copy "cyber_req: ^1.0.1" to clipboard
cyber_req: ^1.0.1 copied to clipboard

retracted

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 Map object for GET requests.

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 (required String): The base URL for all API requests.
  • bearerToken (String?): An optional bearer token to be included in the Authorization header for all requests made with this instance.
  • httpClient (http.Client?): An optional custom http.Client instance. Useful for testing or advanced configurations.
  • onUnauthorized (UnauthorizedHandler?): An optional callback Future<void> Function() that is invoked when a 401 Unauthorized response 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 a GET request.

    • endpoint (String): The API endpoint relative to the baseUrl.
    • 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 (2xx status code).
    • onFailure (FailureCallback?): Callback invoked on API error (4xx or 5xx status 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 a POST request.

    • endpoint (String): The API endpoint.
    • data (Map<String, dynamic>?): The request body, which will be JSON-encoded.
    • (Other parameters are similar to get method)
  • 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 a PUT request.

    • endpoint (String): The API endpoint.
    • data (Map<String, dynamic>?): The request body, which will be JSON-encoded.
    • (Other parameters are similar to get method)
  • Future<Map<String, dynamic>> delete(String endpoint, {Map<String, String>? extraHeaders, String? bearerToken, SuccessCallback? onSuccess, FailureCallback? onFailure, List<int>? allowedStatusCodes}) Makes a DELETE request.

    • endpoint (String): The API endpoint.
    • (Other parameters are similar to get method)

Exceptions #

cyber_req throws specific exceptions to help you handle different error scenarios.

  • ApiException Thrown for general API errors (e.g., 4xx, 5xx status codes, network issues).

    • message (String): A descriptive error message.
    • statusCode (int?): The HTTP status code, if available.
  • UnauthorizedException A specialized ApiException thrown specifically when a 401 Unauthorized status 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.

2
likes
0
points
39
downloads

Publisher

unverified uploader

Weekly Downloads

A flexible API client for Laravel backends with dynamic headers, bearer token support, and callbacks.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

http

More

Packages that depend on cyber_req