Learn Dart #8: Perform a serverside POST request in under 30 seconds
In today’s quick tip we will be using the inbuilt HttpClient
class to perform a server-side POST request.
Watch the video
Below is the full solution:
import 'dart:io';
import 'dart:convert';
main() async {
var apiUrl = Uri.parse('https://jsonplaceholder.typicode.com/posts');
var client = HttpClient(); // `new` keyword optional
// 1. Create request
HttpClientRequest request = await client.postUrl(apiUrl);
// 2. Add payload to request
var payload = {
'title': 'Post 1',
'content': 'Lorem ipsum dolor sit amet',
};
request.write(json.encode(payload));
// 3. Send the request
HttpClientResponse response = await request.close();
// 4. Handle the response
var resStream = response.transform(Utf8Decoder());
await for (var data in resStream) {
print('Received data: $data');
}
}
I’ll admit it’s a bit verbose. However the Dart team created a library called http to simplify this logic.
To install, update your pubspec.yaml
file:
name: dart_project
dependencies:
http: ^0.12.0
And run pub get
to update your dependencies.
Here’s what the solution now looks like:
import 'package:http/http.dart' as http;
void main() async {
var response = await http.post('https://jsonplaceholder.typicode.com/posts',
body: {
'title': 'Post 1',
'content': 'Lorem ipsum dolor sit amet',
});
print(response.body);
}
And run:
$ dart bin/main.dart
# Result:
# {
# "title": "Post 1",
# "content": "Lorem ipsum dolor sit amet",
# "id": 101
# }