op_rest_api_client 0.13.0
op_rest_api_client: ^0.13.0 copied to clipboard
A Dart http client to send requests to REST API.
op_rest_api_client #
A lightweight, extensible Dart package for interacting with RESTful APIs.
Provides automatic serialization, robust error handling, authentication, and identity management while leveraging op_result for structured responses.
🚀 Features #
- 🔄 Simplified API requests:
GET,POST,PUT,PATCH,DELETE - 🔐 Automatic authentication: Supports
Identity-based token handling - ❌ Error handling: Returns structured
OpResult<http.Response>with failure reasons - 🎯 Enum-based endpoint management: Type-safe API endpoint mappings
- 🚧 Built-in token refresh support (auto-retries expired tokens)
- ✅ Strongly typed responses using
OpResult
📦 Installation #
Add op_rest_api_client to your pubspec.yaml:
dependencies:
op_rest_api_client: ^0.12.0
Or install via CLI:
dart pub add op_rest_api_client
🛠️ Usage #
1️⃣ Define API Endpoints as an Enum #
enum MyApiEndpoints {
getUser,
updateUser,
deleteUser,
}
2️⃣ Initialize the API Client #
import 'package:op_rest_api_client/op_rest_api_client.dart';
import 'package:http/http.dart' as http;
final apiClient = OpRestApiClient<MyApiEndpoints>(
baseUrl: "https://api.example.com",
client: http.Client(),
enumValues: MyApiEndpoints.values,
endpointMap: {
MyApiEndpoints.getUser: "/user",
MyApiEndpoints.updateUser: "/user/update",
MyApiEndpoints.deleteUser: "/user/delete",
},
);
3️⃣ Send API Requests #
🔹 GET Request
final result = await apiClient.sendGet(
apiEndPoint: MyApiEndpoints.getUser,
identity: userIdentity, // Optional authentication
);
if (result.isSuccess) {
print("User data: \${result.data.body}");
} else {
print("Error: \${result.error.getErrorMessage()}");
}
🔹 POST Request (With Body)
final newUser = {
'name': 'John Doe',
'email': '[email protected]',
};
final result = await apiClient.sendPost(
apiEndPoint: MyApiEndpoints.updateUser,
identity: userIdentity,
body: newUser,
);
if (result.isSuccess) {
print("User updated successfully!");
} else {
print("Error: \${result.error.getErrorMessage()}");
}
🔹 DELETE Request
final result = await apiClient.sendDelete(
apiEndPoint: MyApiEndpoints.deleteUser,
identity: userIdentity,
);
if (result.isSuccess) {
print("User deleted!");
} else {
print("Error: \${result.error.getErrorMessage()}");
}
📌 Authentication & Token Refresh #
The client supports authentication via Identity, handling token refresh automatically.
final userIdentity = Identity(
accessToken: "abc123",
refreshToken: "refresh123",
refreshCallback: (oldToken) async {
// Refresh token logic (example)
return Identity(
accessToken: "newAccessToken",
refreshToken: "newRefreshToken",
);
},
);
- If a request fails due to an expired token (401):
- The client automatically attempts token refresh.
- If refresh succeeds, the request is retried with the new token.
- If refresh fails, an unauthenticated error is returned.
❌ Error Handling #
All API responses are wrapped in OpResult<http.Response>, which indicates success or failure.
🔄 Customizing Error Handling #
You can also define custom status code mappings:
final result = await apiClient.sendGet(
apiEndPoint: MyApiEndpoints.getUser,
errorHttpStatusCodes: {
ApiErrorType.notFound: [404],
ApiErrorType.unauthenticated: [401],
},
);
🛠 Advanced Configuration #
🌐 Custom Headers #
await apiClient.sendGet(
apiEndPoint: MyApiEndpoints.getUser,
headers: {
"X-Custom-Header": "value",
},
);
📜 Enforcing Response Type #
If an API is expected to return a certain content type (e.g. JSON) but sometimes it doesn't, then the optional responseMapper parameter can be used to enforce that format:
final apiClient = OpRestApiClient<MyApiEndpoints>(
baseUrl: "https://api.example.com",
client: http.Client(),
enumValues: MyApiEndpoints.values,
endpointMap: {
MyApiEndpoints.getUser: "/user",
},
responseMapper: (http.Response response) {
return enforceJsonApiResponse(response);
},
);
🚀 Why Use op_rest_api_client? #
✔ Structured API calls → No need to manage HTTP manually.
✔ Authentication & token refresh → Handles 401 errors automatically.
✔ Strong typing with enums → Prevents invalid API endpoints.
✔ Full OpResult support → Clear success/failure responses.
✔ Custom error handling → Map HTTP codes to app-specific errors.
📌 Versioning & Changelog #
For release history and breaking changes, check the CHANGELOG.
⚖ License #
This project is licensed under thd BSD 3-Clause License.