Creative Bracket

Learn Dart #8: Perform a serverside POST request in under 30 seconds

Hello friends. In today’s quick tip we will be using the inbuilt HttpClient class to perform a server-side POST request.


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
# }

Further reading


Sharing is caring 🤗

If you enjoyed reading this post, please share this through the various social buttons hovering on the left/top side of the screen ↖️⬆️. Also, check out and subscribe to my YouTube channel (hit the bell icon too) for videos on Dart.

Subscribe to my email newsletter to download my Free 35-page eBook titled Get started with Dart and to be notified when new content is released.

Like, share and follow me 😍 for more content on Dart.

Jermaine Oppong

Hello 👋, I show programmers how to build full-stack web applications with the Dart SDK. I am passionate about teaching others, having received tremendous support on sites like dev.to and medium.com for my articles covering various aspects of the Dart language and ecosystem.