DartAdvanced 2 min read

Dart Shelf server tutorial: your first JSON endpoint

Create a local HTTP server, return JSON and verify the endpoint with a real request.

On this page

Start with one health endpoint so you can verify the SDK, dependency graph and listener independently of a database. This example runs locally in the Dart VM, not in DartPad or a static web host.

Create the project

dart create -t console shelf_lab
cd shelf_lab
dart pub add shelf

Create bin/server.dart with this complete entry point:

import 'dart:convert';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

Future<void> main() async {
  final app = const Pipeline().addMiddleware(logRequests()).addHandler((request) {
    if (request.method == 'GET' && request.url.path == 'health') {
      return Response.ok(jsonEncode({'status': 'ok'}),
          headers: {'content-type': 'application/json; charset=utf-8'});
    }
    return Response.notFound('Route not found.');
  });
  final server = await shelf_io.serve(app, '127.0.0.1', 8080);
  print('Listening at http://${server.address.host}:${server.port}');
}

Run dart run bin/server.dart. In another terminal, request http://127.0.0.1:8080/health. With curl use curl -i http://127.0.0.1:8080/health; in Windows PowerShell use curl.exe to select the curl executable explicitly.

Follow the request

A Shelf Handler maps a Request to a Response or future Response. Pipeline composes middleware around that handler. The request URL path used here is relative and has no leading slash, which differs from the route strings used by shelf_router in the full project.

The Content-Type header identifies the JSON representation. Returning a map’s debug string is not equivalent to encoding JSON. Inspect both headers and body rather than assuming a browser showing text proves the contract.

Verify the negative path

Request /missing and confirm a 404. Stop the process and verify the port is no longer serving it. If startup fails because the port is occupied, identify the owning process or choose another port; do not stop an unrelated service blindly.

Exercise

Add a deliberate /version endpoint with a stable JSON field. Then move to the full task API to practise routing, validation and testable application construction. Keep this first listener on loopback while learning.

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.