패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.1.36

api_manager

flutter dio api를 활용하여 API 요청을 쉽게 관리할 수 있는 간단한 패키지입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
301
좋아요
25
Pub 점수
140

패키지 설치

flutter pub add api_manager

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Dio HTTP 클라이언트를 사용하여 API 요청 관리를 간소화하도록 설계된 가벼운 Flutter 패키지입니다. HTTP 호출, 응답 처리 및 프로젝트 전반에서 일관된 오류 관리를 위한 사용하기 쉬운 인터페이스를 제공합니다. 개발자 경험을 최우선으로 고려하여 제작되었으며, 인증 헤더, 요청 인터셉션, 응답 파싱과 같은 일반적인 작업을 간편하게 처리할 수 있습니다. 신뢰성 있고 유지보수가 가능한 네트워크 통신이 필요한 앱에 적합합니다.

사용 사례

  • REST API 호출 처리
  • 인증 토큰 관리
  • API 엔드포인트 중앙화
  • 오류 처리 및 재시도 로직
  • 요청/응답 로깅
  • 네트워크 계층 코드 간소화

주요 기능

  • Dio 위에 구축됨
  • 간편한 구성 및 설정
  • 인터셉터를 지원합니다
  • 자동 오류 처리
  • 모듈형 및 재사용 가능한 디자인
  • 관심사의 명확한 분리

적합한 대상

  • Flutter 초보자가 네트워킹을 배우는 방법
  • 일관된 API 패턴이 필요한 프로젝트
  • 여러 API 엔드포인트를 가진 앱
  • 유지보수 가능한 코드를 우선시하는 팀
  • 최소한의 보일러플레이트를 원하는 개발자

고려 사항

  • Dio 기본 사항에 대한 이해가 필요합니다
  • HTTP 요청에 제한됨(WebSocket 지원 없음)
  • 복잡한 인증 흐름을 위해 추가 설정이 필요할 수 있습니다
  • 사전 맞춤 설정 없이 대규모 기업용 앱에는 적합하지 않습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

api_manager pub package

A simple flutter API to manage rest api request easily with the help of flutter dio.

Get started

Install

Add dependency

pub package

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.responseBodyWrapper('data'); /// This is used to parse the response without data attribute, some use case will shown below
    _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',
    );
  }

카테고리

의존성

의존성 목록 2 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.