JSON response
- Dart course
- Advanced
- Lesson 29/83
- 5 min
Learn JSON responses with shelf.
JSON responses
To return JSON from shelf, use Response.ok(jsonEncode(data), headers: {'content-type': 'application/json'}). jsonEncode comes from dart:convert; it turns Maps and Lists into JSON text.
The content-type header matters; browsers and clients parse the body as JSON. Without it, the body is treated as plain text and not auto-parsed.
Example: Response.ok(jsonEncode({'name': 'Ayşe'}), headers: {'content-type': 'application/json'}). This returns a 200 status with a JSON body.
The JSON content-type header
The headers parameter takes a Map<String, String> and sets response headers. For JSON, {'content-type': 'application/json'} is standard; it tells the client how to parse the body.
Header keys are case-insensitive; Content-Type and content-type are processed the same way. Values are sent as-is.
Multiple headers can be set: headers: {'content-type': 'application/json', 'cache-control': 'no-cache'}. cache-control controls browser caching.
Practice Return a JSON response
Add import 'package:shelf/shelf.dart'; import 'dart:convert';. Define Response userHandler(Request r) => Response.ok(jsonEncode({'name': 'Ayşe'}), 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 userHandler
// call the handler; read JSON body async and print
}Sample solution
import 'package:shelf/shelf.dart';
import 'dart:convert';
Response userHandler(Request r) =>
Response.ok(jsonEncode({'name': 'Ayşe'}),
headers: {'content-type': 'application/json'});
void main() async {
var resp = userHandler(Request('GET', Uri.parse('http://localhost/')));
print(await resp.readAsString());
}Expected output
{"name":"Ayşe"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 JSON encode
var body = ____({'name': 'Ayşe'});
var body = jsonEncode({'name': 'Ayşe'});
Explanation: jsonEncode turns a Map into JSON text.
2 Match the JSON parts
| Term | Meaning |
|---|---|
jsonEncode |
Map → String |
application/json |
Content type |
headers |
Header map |
Response.ok |
200 response |
3 Which header is required for JSON?
- content-type Correct answer
- host
- accept
- user-agent
Explanation: the content-type: application/json header is required.