Summary - Shelf
- Dart course
- Advanced
- Lesson 30/83
- 5 min
Combine Handler, Middleware and Router to write an API.
Summary - Shelf
This group covered the shelf HTTP framework: handler (Request → Response), middleware (handler wrapping), shelf_router (URL routing), JSON responses.
Core: a handler is a function; it is wrapped by middleware; a Router maps URLs to handlers; JSON needs jsonEncode + a content-type header.
It connects to HttpServer via shelf_io; for testing, handlers can be called directly.
Practice Summary: handler + JSON
Add import 'package:shelf/shelf.dart'; import 'dart:convert';. Define Response healthHandler(Request r) => Response.ok(jsonEncode({'status': 'ok'}), headers: {'content-type': 'application/json'});. Make main async; call the handler and add print(await resp.readAsString());.
Starter code
void main() {
// add shelf and dart:convert imports; define healthHandler
// call the handler; print JSON body
}Sample solution
import 'package:shelf/shelf.dart';
import 'dart:convert';
Response healthHandler(Request r) =>
Response.ok(jsonEncode({'status': 'ok'}),
headers: {'content-type': 'application/json'});
void main() async {
var resp = healthHandler(Request('GET', Uri.parse('http://localhost/')));
print(await resp.readAsString());
}Expected output
{"status":"ok"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is required for JSON?
- Router
- content-type header Correct answer
- Isolate
- Future.delayed
Explanation: JSON requires the content-type: application/json header.
2 Match the concepts
| Term | Meaning |
|---|---|
Handler |
Request → Response |
Middleware |
Handler wrapping |
Router |
URL → handler |
jsonEncode |
Map → String |
3 200 response
return ____.ok('merhaba');
return Response.ok('merhaba');
Explanation: Response.ok creates a 200 response.