DartProjects 6 min read

Dart REST API project: complete task service with source and tests

Run a complete local Shelf API, inspect the source and extend it through tested steps.

On this page

Build a task service used by a small operations dashboard. This project ties together classes, JSON, validation, futures, routing, dependency ownership and tests. It is original course source and uses a process-local repository so you can run it without configuring a database first.

Download and run

Download the complete Dart task API project . Extract the archive, open the dart-tasks-api directory and run:

dart pub get
dart analyze
dart test
dart run bin/server.dart

The default listener is http://127.0.0.1:8080. Use HOST and PORT only when intentionally changing the listener. The program does not install or start a cloud service for you.

Read the project layout

bin/server.dart          listener and runtime configuration
lib/tasks_api.dart       models, repository, validation and handlers
test/tasks_api_test.dart request/response and rejection tests
test/socket_test.dart    real loopback HTTP smoke flow
Dockerfile              separate-host container starting point
pubspec.yaml            declared package and SDK constraints

Verify one complete workflow

Create a task with POST /tasks and JSON {"title":"Send invoice"}. Read its Location path. PATCH that task with {"done":true}, then DELETE it. Expect statuses 201, 200, 200 and 204 respectively; reading it after deletion should return 404.

Inspect the REST contract for list pagination and the validation lesson for rejected input. The title policy is deliberately small and explicit rather than an entire task-management product.

Application source

The code below is read from the same checked-in file included in the download during the static build. The article and the ZIP therefore share one source for this implementation.

lib/tasks_api.dart

import 'dart:convert';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';

final class ApiProblem implements Exception {
  const ApiProblem(this.status, this.code, this.message);
  final int status;
  final String code;
  final String message;
}

final class Task {
  const Task({required this.id, required this.title, this.done = false});
  final int id;
  final String title;
  final bool done;

  Map<String, Object> toJson() => {'id': id, 'title': title, 'done': done};
}

// One repository belongs to one app instance. This teaching store is ephemeral.
final class TaskStore {
  final Map<int, Task> _tasks = {};
  int _nextId = 1;

  List<Task> list({required int offset, required int limit}) =>
      _tasks.values.skip(offset).take(limit).toList(growable: false);

  Task? find(int id) => _tasks[id];

  Task create(String title) {
    final task = Task(id: _nextId++, title: title);
    _tasks[task.id] = task;
    return task;
  }

  Task update(int id, {String? title, bool? done}) {
    final old = _tasks[id];
    if (old == null)
      throw const ApiProblem(404, 'not_found', 'Task not found.');
    final changed = Task(
      id: id,
      title: title ?? old.title,
      done: done ?? old.done,
    );
    _tasks[id] = changed;
    return changed;
  }

  bool remove(int id) => _tasks.remove(id) != null;
}

Response jsonResponse(
  int status,
  Object body, {
  Map<String, String>? headers,
}) => Response(
  status,
  body: jsonEncode(body),
  headers: {
    'content-type': 'application/json; charset=utf-8',
    'cache-control': 'no-store',
    ...?headers,
  },
);

String titleFrom(Object? value) {
  if (value is! String || value.trim().isEmpty || value.trim().length > 120) {
    throw const ApiProblem(
      400,
      'invalid_title',
      'Title must contain 1–120 characters.',
    );
  }
  return value.trim();
}

int boundedInt(String? value, {required int fallback, required int max}) {
  if (value == null) return fallback;
  final parsed = int.tryParse(value);
  if (parsed == null || parsed < 0 || parsed > max) {
    throw const ApiProblem(
      400,
      'invalid_query',
      'Pagination parameter is out of range.',
    );
  }
  return parsed;
}

int taskId(String raw) {
  final id = int.tryParse(raw);
  if (id == null || id < 1) {
    throw const ApiProblem(
      400,
      'invalid_id',
      'Task ID must be a positive integer.',
    );
  }
  return id;
}

Future<Map<String, dynamic>> readObject(Request request) async {
  if (request.headers['content-type']?.split(';').first.trim().toLowerCase() !=
      'application/json') {
    throw const ApiProblem(
      415,
      'unsupported_media_type',
      'Use application/json.',
    );
  }
  final bytes = <int>[];
  await for (final chunk in request.read()) {
    if (bytes.length + chunk.length > 16 * 1024) {
      throw const ApiProblem(
        413,
        'body_too_large',
        'JSON body exceeds 16 KiB.',
      );
    }
    bytes.addAll(chunk);
  }
  try {
    final value = jsonDecode(utf8.decode(bytes));
    if (value is Map<String, dynamic>) return value;
  } on FormatException {
    throw const ApiProblem(
      400,
      'invalid_json',
      'Request body is not valid UTF-8 JSON.',
    );
  }
  throw const ApiProblem(
    400,
    'invalid_json',
    'Request body must be a JSON object.',
  );
}

Middleware handleProblems() =>
    (Handler inner) => (Request request) async {
      try {
        return await inner(request);
      } on ApiProblem catch (error) {
        return jsonResponse(error.status, {
          'error': {'code': error.code, 'message': error.message},
        });
      } catch (_) {
        // Production logging belongs on the server; never return stack traces here.
        return jsonResponse(500, {
          'error': {'code': 'internal_error', 'message': 'Request failed.'},
        });
      }
    };

Handler createApp({TaskStore? store}) {
  final repository = store ?? TaskStore();
  final router = Router();
  router.get(
    '/health',
    (Request request) => jsonResponse(200, {'status': 'ok'}),
  );
  router.get('/tasks', (Request request) {
    final query = request.url.queryParameters;
    final offset = boundedInt(query['offset'], fallback: 0, max: 1000000);
    final limit = boundedInt(query['limit'], fallback: 20, max: 100);
    return jsonResponse(200, {
      'items': repository
          .list(offset: offset, limit: limit)
          .map((task) => task.toJson())
          .toList(),
      'offset': offset,
      'limit': limit,
    });
  });
  router.post('/tasks', (Request request) async {
    final input = await readObject(request);
    if (input.keys.any((key) => key != 'title')) {
      throw const ApiProblem(
        400,
        'unknown_field',
        'Only title is accepted when creating a task.',
      );
    }
    final task = repository.create(titleFrom(input['title']));
    return jsonResponse(
      201,
      task.toJson(),
      headers: {'location': '/tasks/${task.id}'},
    );
  });
  router.get('/tasks/<id|[0-9]+>', (Request request, String id) {
    final task = repository.find(taskId(id));
    if (task == null)
      throw const ApiProblem(404, 'not_found', 'Task not found.');
    return jsonResponse(200, task.toJson());
  });
  router.patch('/tasks/<id|[0-9]+>', (Request request, String id) async {
    final input = await readObject(request);
    if (input.isEmpty ||
        input.keys.any((key) => key != 'title' && key != 'done')) {
      throw const ApiProblem(
        400,
        'invalid_patch',
        'Provide title and/or done only.',
      );
    }
    if (input.containsKey('done') && input['done'] is! bool) {
      throw const ApiProblem(400, 'invalid_done', 'done must be a boolean.');
    }
    final title = input.containsKey('title') ? titleFrom(input['title']) : null;
    final task = repository.update(
      taskId(id),
      title: title,
      done: input['done'] as bool?,
    );
    return jsonResponse(200, task.toJson());
  });
  router.delete('/tasks/<id|[0-9]+>', (Request request, String id) {
    if (!repository.remove(taskId(id))) {
      throw const ApiProblem(404, 'not_found', 'Task not found.');
    }
    return Response(204, headers: {'cache-control': 'no-store'});
  });
  router.all(
    '/<path|.*>',
    (Request request) => jsonResponse(404, {
      'error': {'code': 'not_found', 'message': 'Route not found.'},
    }),
  );
  return const Pipeline()
      .addMiddleware(handleProblems())
      .addHandler(router.call);
}

Listener and lifecycle

bin/server.dart

import 'dart:io';
import 'package:fever_tasks_api/tasks_api.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

Future<void> main() async {
  final portText = Platform.environment['PORT'] ?? '8080';
  final port = int.tryParse(portText);
  if (port == null || port < 1 || port > 65535) {
    throw ArgumentError('PORT must be an integer between 1 and 65535.');
  }
  final host = Platform.environment['HOST'] ?? '127.0.0.1';
  final server = await shelf_io.serve(createApp(), host, port);
  server.autoCompress = true;
  print('Learning API: http://${server.address.host}:${server.port}');
  print('In-memory data; no authentication. Keep local until hardened.');
  if (!Platform.isWindows) {
    ProcessSignal.sigterm.watch().listen((_) => server.close());
    ProcessSignal.sigint.watch().listen((_) => server.close());
  }
}

The application factory owns one repository instance. A test can create another application without inheriting the first application’s data. The listener chooses a configured port and enables response compression. Native signal handling depends on the host platform; check the real deployment’s shutdown contract.

Production boundary

Data disappears after a restart. The service has no user authentication or ownership policy and should remain a local learning service until those are implemented. Do not expose it as a multi-user production API just because its CRUD tests pass. Follow authentication , PostgreSQL and deployment before handling real user data.

Project extensions

Add a due date with explicit omission/null semantics, test invalid timestamps and preserve the existing routes. Then refactor an asynchronous repository interface for durable storage. Keep the HTTP contract tests passing while replacing the adapter; this is stronger evidence than rewriting the same test to match a new implementation.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.