POST
- Dart course
- Advanced
- Lesson 33/83
- 5 min
Learn POST requests with http.post.
POST requests
post(url, headers: ..., body: ...) makes a POST request. body can be a String, Map or List<int>. To send JSON, convert to a String with jsonEncode(map).
Example: var r = await post(url, headers: {'content-type': 'application/json'}, body: jsonEncode({'name': 'Ayşe'}));. The server creates a new resource.
POST carries a body; GET does not. Use POST to create data, PUT to update.
Preparing a JSON body
To send a JSON body, first produce a String with jsonEncode(map), then pass it to post with the content-type: application/json header.
Example: var body = jsonEncode({'title': 'Book', 'price': 42});. This String goes into post(url, headers: {'content-type': 'application/json'}, body: body).
Without the header the server may not recognize the body as JSON; therefore content-type is mandatory.
Practice Prepare a JSON body and print it
Add import 'dart:convert';. Inside main add var body = jsonEncode({'title': 'Kitap', 'price': 42});. Add print(body);.
Starter code
void main() {
// add dart:convert import; turn Map into JSON; print
}Sample solution
import 'dart:convert';
void main() {
var body = jsonEncode({'title': 'Kitap', 'price': 42});
print(body);
}Expected output
{"title":"Kitap","price":42}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the POST parts
| Term | Meaning |
|---|---|
post(url, body:) |
POST function |
body |
Sent data |
jsonEncode |
Map → String |
content-type |
Content type |
2 Which header is required to send JSON via POST?
- content-type Correct answer
- host
- user-agent
- accept
Explanation: the content-type: application/json header is required.
3 JSON body
var body = ____({'title': 'Kitap', 'price': 42});
var body = jsonEncode({'title': 'Kitap', 'price': 42});
Explanation: jsonEncode turns a Map into a JSON String.