api_manager 0.1.34 api_manager: ^0.1.34 copied to clipboard
A simple package for manage api request easily with the help of flutter dio api.
api_manager #
A simple flutter API to manage rest api request easily with the help of flutter dio.
Get started #
Install #
Add dependency #
dependencies:
api_manager: $latest_version
Super simple to use #
import 'package:api_manager/api_manager.dart';
void main() async {
ApiResponse response = await ApiManager().request(
requestType: RequestType.GET,
route: "your route",
);
print(response);
}
Config in a base manager #
class ApiRepository {
static final ApiRepository _instance = ApiRepository._internal(); /// singleton api repository
ApiManager _apiManager;
factory ApiRepository() {
return _instance;
}
/// base configuration for api manager
ApiRepository._internal() {
_apiManager = ApiManager();
_apiManager.options.baseUrl = BASE_URL; /// EX: BASE_URL = https://google.com/api/v1
_apiManager.options.connectTimeout = 100000;
_apiManager.options.receiveTimeout = 100000;
_apiManager.enableLogging(responseBody: true, requestBody: false); /// enable api logging EX: response, request, headers etc
_apiManager.enableAuthTokenCheck(() => "access_token"); /// EX: JWT/PASSPORT auth token store in cache
}
}
Examples #
Suppose we have a response model like this:
class SampleResponse{
String name;
int id;
SampleResponse.fromJson(jsonMap):
this.name = jsonMap['name'],
this.id = jsonMap['id'];
}
and actual api response json structure is:
{
"data": {
"name": "md afratul kaoser taohid",
"id": "id"
}
}
#Now we Performing a GET
request :
Future<ApiResponse<SampleResponse>> getRequestSample() async =>
await _apiManager.request<SampleResponse>(
requestType: RequestType.GET,
route: 'api_route',
requestParams: {"userId": 12}, /// add params if required
isAuthRequired: true, /// by set it to true, this request add a header authorization from this method enableAuthTokenCheck();
responseBodySerializer: (jsonMap) {
return SampleResponse.fromJson(jsonMap); /// parse the json response into dart model class
},
);
#Now we Performing a POST
request :
Future<ApiResponse<SampleResponse>> postRequestSample() async =>
await _apiManager.request<SampleResponse>(
requestType: RequestType.POST,
route: 'api_route',
requestBody: {"userId": 12}, /// add POST request body
isAuthRequired: true, /// by set it to true, this request add a header authorization from this method enableAuthTokenCheck();
responseBodySerializer: (jsonMap) {
return SampleResponse.fromJson(jsonMap); /// parse the json response into dart model class
},
);
#Now er performing a multipart file upload request :
Future<ApiResponse<void>> updateProfilePicture(
String filePath,
) async {
MultipartFile multipartFile =
await _apiManager.getMultipartFileData(filePath);
FormData formData = FormData.fromMap({'picture': multipartFile});
return await _apiManager.request(
requestType: RequestType.POST,
isAuthRequired: true,
requestBody: formData,
route: 'api_route',
);
}