op_rest_api_client 0.15.1 copy "op_rest_api_client: ^0.15.1" to clipboard
op_rest_api_client: ^0.15.1 copied to clipboard

A lightweight and flexible Dart HTTP client for RESTful APIs with structured error handling via op_result and support for identity-based authentication and token refresh.

Changelog #

[0.15.1] - 2025-07-22 #

  • Added dnsFailure to OpRestApiErrorType to distinguish DNS resolution issues from other network errors.
  • Upgrade http package to latest version (1.4.0)

[0.15.0] - 2025-07-14 #

Breaking changes #

  • OpRestApiIdentity.authorizationHeader() now returns String? instead of String.
    • Return null to omit the header entirely.
  • OpRestApiErrorType.networkError has been removed and replaced with three more specific error types:
    • networkOffline: device has no internet connection.
    • networkUnreachable: the device is connected but cannot reach the server (e.g., DNS failure, socket exception, timeout).
    • gatewayError: the server responded with a 502 or 504 gateway error.
    • Unified identity header handling: Removed authorizationHeader() from OpRestApiIdentity. Use headers() instead and include Authorization as a regular entry if needed.

Enhancements #

  • Improved error classification for more accurate handling and messaging of network-related failures.

0.14.1 - 2025-04-25 #

Enhancements #

  • Fixed an issue in the README file.
  • Updated ExceptionHandler to classify ClientException as a network error.
  • Updated description in pubspec.yaml to mention support for op_result and identity-based token handling.
  • Added homepage links in pubspec.yaml.
  • Upgraded dependencies to latest stable versions.

0.14.0 - 2025-03-07 #

Added #

  • OpRestApiEndpoint as a replacement for raw endpoint strings.
    • endpointMap now maps user-defined ApiEndpointEnum values to OpRestApiEndpoint instead of String.
  • customValidator as a replacement for errorHttpStatusCodes and successHttpStatusCodes,
  • send() as the new unified request method.

Breaking Changes #

  • Removed sendGet, sendPost, sendPut, sendPatch, and sendDelete
    • The HTTP method is now determined directly from OpRestApiEndpoint.
  • Removed successHttpStatusCodes and errorHttpStatusCodes.
    • These were previously used to determine response success and failure based on predefined status codes.
    • This functionality is now fully replaced by customValidator, which allows more flexible validation based on response body and status code.
  • Removed enumValues and endpointMap.
  • Renamed ApiClientMethods to OpRestApiClientMethods
  • Renamed ApiErrorType to OpRestApiErrorType
  • Renamed Identity to OpRestApiIdentity
  • Renamed restApiBodyEncoder to opRestApiBodyEncoder

Migration Guide #

  • Update endpointMap to use OpRestApiEndpoint instead of String:

    const Map<ApiEndpoints, OpRestApiEndpoint> apiEndpointMap = {
    ApiEndpoints.getUser: OpRestApiEndpoint('/user', OpRestApiClientMethods.get),
    ApiEndpoints.updateUser: OpRestApiEndpoint('/user/update', OpRestApiClientMethods.put),
    };
    
    copied to clipboard
  • Replace calls to sendGet(), sendPost(), etc. with send():

    // Before
    await apiClient.sendGet(endpoint: ApiEndpoints.getUser);
    
    copied to clipboard
    // After
    await apiClient.send(endpoint: ApiEndpoints.getUser);
    
    copied to clipboard
  • If you previously used successHttpStatusCodes and errorHttpStatusCodes, migrate to customValidator:

    // Before (Using `successHttpStatusCodes` & `errorHttpStatusCodes`)
    final result = await apiClient.send(
      endpoint: MyApiEndpoints.getUser,
      successHttpStatusCodes: [200, 202], // Considered successful
      errorHttpStatusCodes: {OpRestApiErrorType.notFound: [404]},
    );  
    
    copied to clipboard
    // After (Using `customValidator`):
    OpResult<http.Response, MyCustomError>? myValidator(http.Response response) {
      if (response.statusCode == 200 || response.statusCode == 202) {
        return OpResult.success(response);
      }
      if (response.statusCode == 404) {
        return OpResult.failure(OpError(type: MyCustomError.notFound));
      }
      return null; // Fallback to default handling
    }
    final result = await apiClient.send(
      endpoint: MyApiEndpoints.getUser,
      customValidator: myValidator,
    );
    
    copied to clipboard

0.13.0 - 2025-03-03 #

Breaking Changes #

  • Renamed package json_api_client to op_rest_api_client
    • Update all import statements:

      // No longer valid:
      import 'package:json_api_client/json_api_client.dart'; 
      // Use this instead:
      import 'package:op_rest_api_client/op_rest_api_client.dart'; 
      
      copied to clipboard
    • Update pubspec.yaml dependencies:

      dependencies:
        op_rest_api_client: ^0.13.0
      
      copied to clipboard

0.12.0 - 2025-03-03 #

Breaking Changes #

  • Renamed ApiOpResult to OpResult for consistency with the package naming convention.
  • Renamed OpResultError to OpError to simplify error handling terminology.
  • Renamed ApiOpResultErrorType to ApiErrorType to better reflect its role as an API-specific error type.

These changes require updating all references to the renamed classes in your codebase.

[0.11.1] - 2025-02-27 #

Upgrades & Improvements #

  • Upgraded to the latest op_result library:
  • Refactored codebase to align with op_result changes:
    • Updated all failure() calls to use the new factory constructor.
    • Ensured compliance with the new multiple error handling system.

[0.11.0] - 2025-02-24 #

New Features #

  • Added Support for PUT, PATCH, and DELETE Methods

    • The API client now supports all major HTTP request methods, including:

      • sendPut()
      • sendPatch()
      • sendDelete()
    • These methods function similarly to sendPost(), allowing request bodies and encoded data.

    • Usage Examples:

      // PUT Request
      final response = await apiClient.sendPut(
        apiEndPoint: ApiEndpoints.updateUser,
        identity: userIdentity,
        body: {"name": "Updated Name", "email": "new@example.com"},
      );
      
      // PATCH Request
      final response = await apiClient.sendPatch(
        apiEndPoint: ApiEndpoints.partialUpdate,
        identity: userIdentity,
        body: {"status": "active"},
      );
      
      // DELETE Request
      final response = await apiClient.sendDelete(
        apiEndPoint: ApiEndpoints.deleteAccount,
        identity: userIdentity,
      );
      
      copied to clipboard
  • Enhanced API Consistency

    • The API client now follows a unified request structure for POST, PUT, PATCH, and DELETE, ensuring consistent handling of request bodies.
    • body and encodedBody work the same way across all methods.
  • Updated Documentation & Macros

    • The DartDoc macros now clarify that:
      • body is optional for DELETE requests.
      • headers["authorization"] cannot be used together with identity, but other headers can be combined.

[0.10.0] - 2025-02-22 #

Enhancements #

  • Added Support for x-www-form-urlencoded Request Body Encoding

    • The API client now supports sending requests using application/x-www-form-urlencoded.
    • If encodedBody is provided, it takes precedence over body, ensuring full control over pre-encoded data.
    • If encodedBody is null, the client automatically encodes body based on the content-type header.
    • Encoding behavior:
      • "application/json" (default) → Encoded as JSON.
      • "application/x-www-form-urlencoded" → Encoded as a query string.
    • Example Usage:
      final response = await apiClient.sendPost(
        apiEndPoint: ApiEndpoints.login,
        identity: null,
        body: {"email": "user@example.com", "password": "123456"},
      ); // Defaults to JSON encoding
      
      copied to clipboard
      final response = await apiClient.sendPost(
        apiEndPoint: ApiEndpoints.login,
        identity: null,
        headers: {"content-type": "application/x-www-form-urlencoded"},
        body: {"email": "user@example.com", "password": "123456"},
      ); // Automatically encodes as form-urlencoded
      
      copied to clipboard
      final response = await apiClient.sendPost(
        apiEndPoint: ApiEndpoints.login,
        identity: null,
        encodedBody: "email=user%40example.com&password=123456",
        headers: {"content-type": "application/x-www-form-urlencoded"},
      ); // Uses pre-encoded body
      
      copied to clipboard
  • New Public Helper: restApiBodyEncoder

    • The package now exports restApiBodyEncoder, a utility function to encode request bodies according to the content-type.
    • Users can use this function if they need to manually encode a request body before passing it to encodedBody.
    • Example Usage:
      import 'package:rest_api_client/rest_api_client.dart';
      
      final String encoded = restApiBodyEncoder(
        {"email": "user@example.com", "password": "123456"},
        "application/x-www-form-urlencoded",
      )!;
      
      print(encoded); // Output: email=user%40example.com&password=123456
      
      copied to clipboard
    • This allows consistency between manual encoding and the library's automatic encoding logic.
  • Updated sendPost Documentation

    • Clarified that body is encoded based on the content-type header, defaulting to application/json.
    • Explicitly documented that encodedBody takes precedence if provided.
    • Improved examples for JSON, form-urlencoded, and manually encoded bodies.

[0.9.0] - 2025-02-14 #

Breaking Changes #

  • Renamed rawToken to identityData

    • This change makes the field name more representative of its purpose, indicating that it holds identity-related authentication data rather than just a raw token.
    • Migration Guide:
      • Update all instances of rawToken to identityData.
    • Example:
      final AuthIdentity identity = ...;
      print(identity.rawToken); // No longer valid
      print(identity.identityData); // Use this instead
      
      copied to clipboard
  • Renamed authToken() to authorizationHeader()

    • This change clarifies that the method returns a properly formatted HTTP Authorization header instead of just a raw token.
    • Migration Guide:
      • Replace calls to authToken() with authorizationHeader().
    • Example:
      final Identity identity = ...;
      final String token = identity.authToken(); // ❌ No longer valid
      final String header = identity.authorizationHeader(); // ✅ Use this instead
      
      copied to clipboard

Enhancements #

  • Improved naming conventions for better clarity and maintainability.
  • Strengthened the API client's consistency in handling authentication.

Migration Notes #

  • All implementations of Identity<T> must update their method signatures to reflect the new names.
  • If using authToken() in API request headers, replace it with authorizationHeader().
  • If storing rawToken, update it to identityData.

[0.8.0] - 2025-02-13 #

Added #

  • Support for Token Refresh:

    • The API client now supports automatic token refresh, ensuring persistent authentication without requiring the user to log in again when their access token expires.
    • When an API request fails with 401 Unauthorized, the client will attempt a token refresh once before retrying the request.
    • If the refresh is successful, the request is retried seamlessly using the new access token.
  • refresh Method in Identity:

    • This new method is responsible for invoking the refresh token flow.
    • It is automatically triggered when the access token is expired or when a 401 response is received from the API.

Fixes & Improvements #

  • Optimized API request handling to automatically retry requests after a successful token refresh.

[0.7.0] - 2025-02-12 #

Breaking Changes #

  • Removed authHeaderKey parameter
    • If needed, custom authorization headers can now be passed directly through the headers parameter in each API call.
    • As a result, when identity is specified in a request, the Authorization header now defaults to 'Bearer $token'.

Enhancements #

  • Flexible Authentication Handling
    • Both headers and identity can now be provided in a request.
    • However, headers['Authorization'] and identity are mutually exclusive—if headers['Authorization'] is explicitly set, identity will be ignored.

[0.6.0] - 2025-02-01 #

Added #

  • Added support for custom headers in OpRestApiClient.
    • Users can now pass an optional headers parameter in API requests, allowing full control over authentication and custom headers.
    • If headers is provided, identity is ignored, making the library independent of the Identity class and more flexible for various authentication methods.
    • This enables the use of API keys, session-based auth, and other custom headers without modifying the core API client.

[0.5.0] - 2025-01-14 #

Added #

  • Added support for an optional onUnauthenticated callback in OpRestApiClient. This callback is triggered when a request returns an unauthenticated error, enabling custom handling of unauthenticated states, such as logging out or displaying a user message.
  • The onUnauthenticated callback supports both synchronous and asynchronous functions, allowing flexibility for diverse use cases.

[0.4.0] - 2025-01-13 #

Added #

  • Introduced authToken() in Identity, providing a method to retrieve the authentication token regardless of the type T of the Identity. This enhances flexibility and ensures a consistent way to access tokens in various implementations.
  • Renamed token in Identity to rawToken to better distinguish it from the authToken() method, which provides a processed or extracted authentication token.

[0.3.0] - 2025-01-13 #

Added #

  • Made Identity a generic class, enabling the usage of tokens with types other than String. This increases flexibility and allows for better type safety in applications that use custom token types.

[0.2.0] - 2025-01-12 #

Added #

  • Introduced an endpoints enum to map API endpoints and validate time. This improves maintainability and consistency when working with API endpoint definitions.

[0.1.0] - 2025-01-06 #

Initial Release #

  • Initial release with core functionality to interact with APIs, including support for basic CRUD operations.
0
likes
160
points
270
downloads

Publisher

verified publishercantini.dev

Weekly Downloads

2024.09.06 - 2025.08.01

A lightweight and flexible Dart HTTP client for RESTful APIs with structured error handling via op_result and support for identity-based authentication and token refresh.

Homepage

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

http, op_result

More

Packages that depend on op_rest_api_client