CodeBlanks Logo Icon CodeBlanks

shelf

Learn HTTP servers with shelf.

The shelf package

shelf is a minimal HTTP server framework for Dart. It takes requests (Request), passes them to a user-defined handler, and returns a Response.

A handler is a function with signature Response Function(Request). shelf calls it; you produce a Response.

shelf itself is not a server; the shelf_io adapter connects it to an HttpServer. This separation makes testing easy and adapters portable.

Responding with Response.ok

Response.ok(body) creates a 200-status response. body can be a String, List<int> or Stream<List<int>>.

Example handler: Response helloHandler(Request req) => Response.ok('merhaba');. This handler returns 200 with body 'merhaba' on every request.

To test the handler, call it directly without starting shelf_io: var r = helloHandler(...); print(r.statusCode);.

Practice Define and call a handler

Add import 'package:shelf/shelf.dart';. Define Response helloHandler(Request req) => Response.ok('merhaba');. In main add var r = helloHandler(Request('GET', Uri.parse('http://localhost/'))); and print(r.statusCode);.

Starter code

main.dart
void main() {
  // add shelf import; define helloHandler (outside main)
  // call the handler and print the status code
}

Sample solution

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

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

void main() {
  var r = helloHandler(Request('GET', Uri.parse('http://localhost/')));
  print(r.statusCode);
}

Expected output

200

Questions and answers

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

1 What is shelf's core abstraction?

  • Handler (Request → Response) Correct answer
  • Stream
  • Widget
  • Future

Explanation: a handler takes a Request and returns a Response.

2 Handler signature

Question
Response helloHandler(____ req) => Response.ok('merhaba');
Answer
Response helloHandler(Request req) => Response.ok('merhaba');

Explanation: a handler takes a Request parameter.

3 Match the shelf concepts

Term Meaning
Request Incoming request
Response Outgoing response
Handler Request → Response
shelf_io HttpServer adapter

All lessons in Advanced