minimal_rest 1.0.3 minimal_rest: ^1.0.3 copied to clipboard
MinRest acts as a REST Client and Service/Datasource and returns data as your `DataModel` or `Entity` whichever object you want.
If you like Either<L, R>
datatype from the dartz
package, and tired of writting boilerplates for consuming REST Api in Either<L, R>
This Package is the solution for you.
MinRest
acts as a REST Client and returns data as your DataModel
or Entity
whichever object you want.
Features #
- Making all kind of
http
request - It returns your
DataModel
by making ahttp
request and returnsEither<YourModel, Error>
Getting started #
You need to Initialize the MinRest
singleton with the base url
Let's do it int the main.dart
file
void main() {
WidgetsFlutterBinding.ensureInitialized();
...
MinRest.init("https://jsonplaceholder.typicode.com/todos/1");
...
runApp(Main());
}
Make a GET
request #
- Your own DataModel class
Let's say we have a
DataModel
namedUserModel
class UserModel {
final String name;
final String email;
UserModel({required this.name, required this.email});
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
name: json['name'],
email: json['email'],
);
}
Map<String, dynamic> toJson() {
return {
'name': name,
'email': email,
};
}
}
- Make the API call and get
Either<MinRestError, UserModel>
final userOrError = await MinRest().getErrorOr<UserModel>(
"/path_to_user_data",
(json) => UserModel.fromJson(json),
);
Note that
MinRestError
is the default error objectMinRest
will return in theLeft
side ofEither
- Fold and using the data
Now you can use
userOrError
just like anyEither<L, R>
object. Let'sfold
userOrError and print thename
andemail
of the user if the request and response is successful. (status code from 200 to 199)- or print the
error
status code andmessage
of the request is failed
userOrError.fold(
(error) => print("Error: ${error.code} - ${error.message}"),
(user) => print("User: ${user.name} - ${user.email}"),
);
Usage #
How to use MinRest
Get Request #
final userOrError = await MinRest().getErrorOr<UserModel>(
"/path_to_user_data",
(json) => UserModel.fromJson(json),
token: token.accessToken,
);
Post Request #
final postData = await MinRest().postErrorOr<UserModel>(
"/path_to_user_data",
userModel.toJson(),
(json) => UserModel.fromJson(json),
token: token.accessToken,
);
Patch Request #
final patchData = MinRest().patchErrorOr<UserModel>(
uri: "/auth/update-profile",
data: userModel.toJson(),
deSerializer: (json) => UserModel.fromJson(json),
errorDeserializer: (json) => AppError.fromJson(json),
token: token.accessToken,
);
Delete Request #
final deleteData = MinRest().deleteErrorOr(
uri: "/auth/delete-account",
deSerializer: (json) => RestResponseNoEntity.fromJson(json),
errorDeserializer: (json) => AppError.fromJson(json),
token: token.accessToken,
)
Here AppError is your custom ErrorModel, (Later this will be implemented in other methods as well, Get and Post methods now returns
MinRestError
only)