CodeBlanks Logo Icon CodeBlanks

Router

Learn routing with shelf_router.

shelf_router

shelf_router is a package that maps URL paths to handlers. You create a Router() and add routes with .add('/path', handler).

There is also an annotation-based API: methods marked with @Route.get('/hello') are wired automatically via Router<MyApi>().add. This works through code generation (source_gen).

A Router is a handler: var handler = Router()..get('/hello', helloHandler);. You can pass this handler to shelf_io.

Multiple routers with Cascade

A Cascade tries multiple handlers; the first successful (200-level) response wins. A handler that returns 404 is skipped and the next is tried.

Usage: var handler = Cascade().add(apiRouter).add(staticHandler).handler;. The API is tried first; if no match, the static file handler.

This is a common pattern for REST API + static file serving.

Practice Add a route with Router

Add import 'package:shelf/shelf.dart'; import 'package:shelf_router/shelf_router.dart';. Define Response helloHandler(Request r) => Response.ok('merhaba');. Make main async; add var router = Router()..get('/hello', helloHandler);, var resp = await router(Request('GET', Uri.parse('http://localhost/hello'))); and print(await resp.readAsString());.

Starter code

main.dart
void main() {
  // add shelf and shelf_router imports; define helloHandler
  // build Router with /hello route; call; print body
}

Sample solution

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

Response helloHandler(Request r) => Response.ok('merhaba');

void main() async {
  var router = Router()..get('/hello', helloHandler);
  var resp = await router(Request('GET', Uri.parse('http://localhost/hello')));
  print(await resp.readAsString());
}

Expected output

merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a Router do?

  • Manages a database
  • Does logging
  • Produces JSON
  • Maps URL paths to handlers Correct answer

Explanation: a router maps URL paths to handlers.

2 Match the Router methods

Term Meaning
.get('/path', h) GET route
.post('/path', h) POST route
.add('/path', h) Manual add
@Route.get Annotation

3 Add a GET route

Question
router.____('/hello', helloHandler);
Answer
router.get('/hello', helloHandler);

Explanation: router.get('/hello', handler) adds a GET route.

All lessons in Advanced