Bones_API는 Dart용 포괄적인 백엔드 프레임워크로 서버 사이드 개발을 간소화하도록 설계되었습니다. 내장된 HTTP 서버, 라우트 및 엔티티 핸들러, SQL 번역기, 데이터베이스 어댑터를 포함하여 빠른 API 생성을 가능하게 합니다. 크로스플랫폼 지원을 갖추고 있어 Android, iOS, Web, macOS, Windows, Linux에서 원활하게 작동합니다. 최소한의 반복 코드로 확장 가능한 API를 구축하기 위한 기능이 풍부하고 통합된 솔루션을 찾는 개발자에게 이상적입니다.
사용 사례
RESTful API 구축
Flutter 앱용 백엔드 서비스 만들기
풀스택 Dart 애플리케이션 개발
SQL을 통한 데이터베이스 상호작용 관리
실시간 데이터 엔드포인트 구현
하나의 코드베이스에서 웹 및 모바일 클라이언트를 제공
주요 기능
내장형 HTTP 서버
경로 및 엔터티 처리
SQL 번역 계층
다중 DB 어댑터 지원
크로스 플랫폼 배포
백엔드 서비스를 위한 최소 설정
적합한 대상
Dart 백엔드 개발자
풀스택 플러터 팀
API 우선 애플리케이션 빌더
데이터베이스 추상화가 필요한 프로젝트
통합 Dart 백엔드 솔루션을 원하는 팀
고려 사항
Dart 백엔드 패턴에 대한 이해가 필요합니다
복잡한 쿼리에 대한 추가 구성이 필요할 수 있습니다
다양한 플랫폼에서 Dart를 사용하는 프로젝트에 가장 적합
더 큰 프레임워크에 비해 커뮤니티 규모가 제한적
안정적인 Dart 생태계의 성숙도에 달려 있음
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
Bones_API
Bones_API - A powerful API backend framework for Dart. It comes with a built-in HTTP Server,
route handler, entity handler, SQL translator, and DB adapters.
Usage
A simple BTC-USD API example:
import'package:bones_api/bones_api_server.dart';
import'package:mercury_client/mercury_client.dart';
/// APIs are organized in modules:classMyBTCModuleextendsAPIModule{
MyBTCModule(APIRoot apiRoot) : super(apiRoot, 'btc');
/// The default route for not matching routes:@overrideString? get defaultRouteName => '404';
/// A configuration property from `apiConfig`.Stringget notFoundMsg => apiConfig['not_found_msg'] ?? 'Unknown route!';
@overridevoidconfigure() {
routes.get('usd', (request) => fetchBtcUsd());
routes.any('time', (request) => APIResponse.ok(DateTime.now()));
routes.any('404', notFound);
}
/// A HTTP client for `fetchBtcUsd`:staticfinal coinDeskClient = HttpClient("https://api.coindesk.com/v1/bpi");
/// Fetches the BTS-USD price.Future<APIResponse<num>> fetchBtcUsd() async {
var response = await coinDeskClient.get('currentprice.json');
if (response.isNotOK) {
returnAPIResponse.notFound();
}
var btcUsd = response.json['bpi']['USD']['rate_float'] asnum?;
return btcUsd != null ? APIResponse.ok(btcUsd) : APIResponse.notFound();
}
/// Not found route (`404`):FutureOr<APIResponse> notFound(request) {
// The requested path:var path = request.path;
var body = '''
<h1>404</h1><br>
<b>PATH:<b> $path
<p>
<i>$notFoundMsg</i>
''';
// `APIResponse` with `content-type` and `cache-control`:returnAPIResponse.notFound(payload: body)
..payloadMimeType = 'text/html'
..headers['cache-control'] = 'no-store';
}
}
/// The `APIRoot` defines the API version and modules to use:classMyAPIextendsAPIRoot{
MyAPI({dynamic apiConfig}) : super('example', '1.0', apiConfig: apiConfig);
// Load the modules used by this API:@overrideSet<APIModule> loadModules() => {MyBTCModule(this)};
}
/// Starts an [APIServer] and calls the routes through [HttpClient]:voidmain() async {
// A JSON to configure the API:var apiConfigJson = '''
{"not_found_msg": "This is 404!"}
''';
var api = MyAPI(apiConfig: apiConfigJson);
int? serverPort = awaitstartAPIServer(api);
var httpClient = HttpClient("http://localhost:$serverPort/");
var btcUsd = (await httpClient.get('/btc/usd')).bodyAsString;
print('BTC-USD: $btcUsd');
var time = (await httpClient.post('/btc/time')).bodyAsString;
print('TIME: $time');
var foo = (await httpClient.get('/btc/foo')).bodyAsString;
print('FOO:\n$foo');
awaitstopAPIServer();
}
latefinalAPIServer apiServer;
/// Starts the [APIServer] (HTTP Server) and returns the port./// - With Hot Reload if `--enable-vm-service` is passed to the Dart VM.Future<int?> startAPIServer(MyAPI api) async {
var serverPort = 8088;
print('Starting APIServer...\n');
apiServer = APIServer(api, '*', serverPort, hotReload: true);
await apiServer.start();
print('\n$apiServer');
print('URL: ${apiServer.url}\n');
return serverPort;
}
/// Stops the [APIServer].Future<bool> stopAPIServer() async {
await apiServer.stop();
returntrue;
}
You can use the package reflection_factory to automate some
declarations.
For example, you can map all routes in a class with one line of code:
File: module_account.dart:
import'package:bones_api/bones_api.dart';
import'package:reflection_factory/reflection_factory.dart';
// See Repositories sections below in this README:import'repositories.dart';
// The generated reflection code by `reflection_factory`:part'module_account.reflection.g.dart';
@EnableReflection()
classAccountModuleextendsAPIModule{
AccountModule(APIRoot apiRoot) : super(apiRoot, 'account');
finalAddressAPIRepository addressRepository = AddressAPIRepository();
finalAccountAPIRepository accountRepository = AccountAPIRepository();
@overridevoidconfigure() {
// Maps the POST routes by reflection of any method in this class// that returns `APIResponse` or accepts `APIRequest`.
routes.postFrom(reflection);
}
// The request parameters will be mapped to the correct// method parameter by name:Future<APIResponse> auth(String? email, String? password) async {
if (email == null) {
returnAPIResponse.error(error: 'Invalid parameters!');
}
if (password == null) {
returnAPIResponse.unauthorized();
}
var sel = await accountRepository.selectAccountByEmail(email);
if (sel.isEmpty) {
returnAPIResponse.unauthorized();
}
var account = sel.first;
// The object `account` will be automatically converted// to JSON when the response is sent through HTTP.return account.checkPassword(password)
? APIResponse.ok(account)
: APIResponse.unauthorized();
}
}
Declaring Entities & Reflection
You can declare entities classes in portable Dart code (that also works in the Browser).
To easily enable toJSon and fromJson, just add @EnableReflection() to your entities.
To stored entities in Databases and manipulate them you can set up an EntityRepositoryProvider:
File: repositories.dart
import'package:bones_api/bones_api.dart';
// Import the PostgreSQL Adapter:import'package:bones_api/bones_api_adapter_postgre.dart';
// Import the above entities file:import'entities.dart';
/// The API `EntityRepositoryProvider`:classAPIEntityRepositoryProviderextendsEntityRepositoryProvider{
staticfinalAPIEntityRepositoryProvider _instance =
APIEntityRepositoryProvider._();
// Singleton:factoryAPIEntityRepositoryProvider() => _instance;
// Returns the current `APIRoot`:APIRoot? get apiRoot => APIRoot.get();
APIEntityRepositoryProvider._() {
// The current APIConfig:var apiConfig = apiRoot?.apiConfig;
var postgreAdapter = PostgreSQLAdapter.fromConfig(
apiConfig?['postgres'], // The connection configuration
parentRepositoryProvider: this,
);
// Join the `PostgreSQLAdapter` and the Address/Account// `EntityHandler` (from reflection) to set up an// `EntityRepository` that uses SQL:// Entity `Address` in table `address`:SQLEntityRepository<Address>(
postgreAdapter, 'address', Address$reflection().entityHandler);
// Entity `Account` in table `account`:SQLEntityRepository<Account>(
postgreAdapter, 'account', Account$reflection().entityHandler);
}
}
/// The [Address] APIRepository:classAddressAPIRepositoryextendsAPIRepository<Address> {
AddressAPIRepository() : super(provider: APIEntityRepositoryProvider());
/// Selects an [Address] by field `state`:FutureOr<Iterable<Address>> selectByState(String state) {
returnselectByQuery(' state == ? ', parameters: {'state': state});
}
}
/// The [Account] APIRepository:classAccountAPIRepositoryextendsAPIRepository<Account> {
AccountAPIRepository() : super(provider: APIEntityRepositoryProvider());
/// Selects an [Account] by field `email`:FutureOr<Iterable<Account>> selectAccountByEmail(String email) {
returnselectByQuery(' email == ? ', parameters: {'email': email});
}
/// Selects an Account by field `address` and sub-field `state`:FutureOr<Iterable<Account>> selectAccountByAddressState(String state) {
// This condition will be translated to a SQL with INNER JOIN (when using an SQLAdapter):returnselectByQuery(' address.state == ? ', parameters: [state]);
}
/// Selects a page of [Account]s by field `state` (`page` starts at 1):FutureOr<Iterable<Account>> selectAccountsPage(String state, int page) {
// `page` computes the offset from the page size, and implies `orderByID`,// so the pagination is stable// (translated to: ORDER BY <id> ASC LIMIT 20 OFFSET <(page - 1) * 20>).returnselectByQuery(
' address.state == ? ',
parameters: [state],
limit: 20,
page: page,
);
}
/// Selects the 10 newest [Account]s (highest IDs first):FutureOr<Iterable<Account>> selectNewestAccounts() {
returnselectAll(
limit: 10,
orderByID: true,
orderDirection: OrderDirection.descending,
);
}
}
Ordering and pagination
The select* methods accept limit, offset, page, orderByID and
orderDirection:
orderByID orders by the table's ID column, resolved automatically from the
table scheme — no column name to spell out.
A non-null offset turns orderByID on by default, since an offset without
a stable order can return overlapping or missing rows across pages. Pass
orderByID: false to opt out.
orderDirection is OrderDirection.ascending by default, and is ignored
while the ordering is not active.
page is the 1-based ergonomic form of offset, using limit as the page
size: page: 3, limit: 20 is offset: 40. It throws an ArgumentError if
combined with an offset, if there is no positive limit to page by, or if
it is below 1.
Paginated reads: EntityPagination
For reading a result page by page, paginateByQuery (and paginate /
paginateAll) returns an EntityPagination, which keeps the pages it has
already loaded:
var page = accountRepository.paginateByQuery(
' address.state == ? ',
parameters: ['NY'],
limit: 20,
);
await page.loadNextPage(); // loads page 1
page[0]; // synchronous: already loaded
page[45]; // null: not loaded (never fetches)await page.getAt(45); // loads page 3 on demand
page.loadedPages; // [1, 3] — page 2 is a gap
page.maxLoadedIndex; // 59
page.totalLength; // null: the end is not known yetawait page.loadAll(); // fills the gaps and resolves the end
page.totalLength; // 57
page.finalPage; // 3
Pages are 1-based and entry indexes 0-based. Synchronous access
(operator [], loadedEntities) never fetches — only the FutureOr methods
(getAt, getPage, getRange, loadNextPage, loadAll, stream) do.
It is deliberately not a List: a paginated select does not know its length
until it reaches the end, so totalLength is null until the final page is
identified (isFinalPageResolved). Until then you still know
maxLoadedIndex, maxKnownPage and which pages are loaded.
The optional onEvent hook reports what is being fetched, for progress
reporting and logging:
Events are delivered synchronously and in order, so the sequence is meaningful
even for a synchronous page loader. To consume them as a Stream instead,
forward them: onEvent: myEventStream.add.
To use a SQL database with your EntityRepository you need a SQLAdapter:
DBPostgreSQLAdapter: a PostgreSQL adapter.
Import: package:bones_api/bones_api_db_postgre.dart
DBMySQLAdapter: a MySQL adapter.
Import: package:bones_api/bones_api_db_mysql.dart
DBSQLiteAdapter: an embedded SQLite adapter, for a database file
or an in-memory database. Needs no server and no native library: the
sqlite3 package bundles SQLite itself.
Import: package:bones_api/bones_api_db_sqlite.dart
DBSQLMemoryAdapter: a portable SQLAdapter that stores entities in memory.
The SQLAdapter is responsible to connect to the database, manage the connection
pool and also to adjust the generated SQLs to the correct dialect.