Getting Started

Products

Infrastructure

Quickstart

Deploy a complete Dart backend with a globally distributed database in under 10 minutes. This quickstart covers creating a Globe DB, writing a full CRUD API with Drift, and testing it live.

Prerequisites

  • A Globe account.
  • The Dart SDK.

1. Create a Database

First, create the database on the Globe dashboard.

  1. Navigate to the Globe dashboard.
  2. Go to the Databases tab and click Create Database.
  3. Select a location for your database.
  4. Click Create, and a name will be automatically assigned to your new database.

This provisions your distributed, serverless SQLite database. Make sure to copy the auto-generated name for the next steps.

2. Set Up the Dart Server Project

Create a new Dart server project by running the following commands in your terminal.

  • Create the project:

    dart create -t server-shelf my_api
    cd my_api
    
  • Add dependencies:

     dart pub add drift sqlite3 dev:drift_dev dev:build_runner
    

3. Define the Database and Tables

Create a new file at lib/database.dart to define your schema with Drift. Remember to replace your-db-name with the name automatically assigned to your database in Step 1.

import 'package:drift/drift.dart';
import 'package:sqlite3/sqlite3.dart';

part '../db/database.g.dart';

// Defines the 'users' table.
@DataClassName('User')
class Users extends Table {
  IntColumn get id => integer().autoIncrement()();
  TextColumn get name => text()();
}

@DriftDatabase(tables: [Users])
class AppDatabase extends _$AppDatabase {
  AppDatabase() : super(_openConnection());

  @override
  int get schemaVersion => 1;

  static QueryExecutor _openConnection() {
    // On deployment, Globe automatically connects this to the live database.
    return NativeDatabase.opened(sqlite3.open('your-db-name.db'));
  }
}

Analyzer errors will be present in database.dart until the necessary helper code is generated in the next step.

4. Generate the Drift Code

Run the build_runner to generate the database.g.dart file.

dart run build_runner build --delete-conflicting-outputs

5. Write the API Logic

Replace the contents of bin/server.dart with this complete CRUD server.

import 'dart:convert';
import 'dart:io';
import 'package:drift/drift.dart';
import 'package:my_api/database.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';

void main(List<String> args) async {
 // Initialize the Drift database
 final db = AppDatabase();

 final app = Router();

 app.get('/users', (Request request) async {
   // Fetch all users using Drift's type-safe API
   final allUsers = await db.select(db.users).get();

   return Response.ok(
     jsonEncode(allUsers.map((user) => user.toJson()).toList()),
     headers: {'Content-Type': 'application/json'},
   );
 });

 app.post('/users', (Request request) async {
   final body = jsonDecode(await request.readAsString());
   final name = body['name'] as String;

   // Insert a new user using Drift's type-safe API
   final user = await db
       .into(db.users)
       .insertReturning(UsersCompanion.insert(name: name));

   return Response.ok(
     jsonEncode(user.toJson()),
     headers: {'Content-Type': 'application/json'},
   );
 });

 app.patch('/users/<id>', (Request request, String id) async {
   final body = jsonDecode(await request.readAsString());
   final newName = body['name'] as String;
   final userId = int.parse(id);

   final count = await (db.update(db.users)..where(
     (tbl) => tbl.id.equals(userId),
   )).write(UsersCompanion(name: Value(newName)));

   if (count == 0) return Response.notFound('User not found');

   return Response.ok('User updated');
 });

 app.delete('/users/<id>', (Request request, String id) async {
   final userId = int.parse(id);
   final count =
       await (db.delete(db.users)..where((tbl) => tbl.id.equals(userId))).go();

   if (count == 0) return Response.notFound('User not found');

   return Response.ok('User deleted');
 });

 final ip = InternetAddress.anyIPv4;
 final handler = Pipeline().addMiddleware(logRequests()).addHandler(app.call);
 final port = int.parse(Platform.environment['PORT'] ?? '8080');
 final server = await serve(handler, ip, port);
 print('✅ Server listening on port ${server.port}');
}

6. Deploy to Globe

Deploy the backend to the Globe platform.

globe deploy --prod

7. Test the Live API

After deployment, test the live API endpoints using curl.

  • Create a user:

    curl -X POST https://your-live-url.globe.app/users \
    -H "Content-Type": "application/json" \
    -d '{"name": "Ada"}'
    
  • Get the list of users:

    curl https://your-live-url.globe.app/users
    
  • Update a user (e.g., the user with ID 1):

     curl -X PATCH https://your-live-url.globe.app/users/1 \
     -H "Content-Type: application/json" \
     -d '{"name": "Ada Lovelace"}'
    
  • Delete a user (e.g., the user with ID 1):

    curl -X DELETE https://your-live-url.globe.app/users/1