# 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

%[https://www.youtube.com/watch?v=Mj7wWWTof7c] 

Below is the full solution:

```dart
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:

```yaml
name: dart_project
dependencies:
  http: ^0.12.0
```

And run `pub get` to update your dependencies.

Here’s what the solution now looks like:

```dart
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:

```bash
$ dart bin/main.dart

# Result:
# {
#   "title": "Post 1",
#   "content": "Lorem ipsum dolor sit amet",
#   "id": 101
# }
```

## **Further reading**

* [**HttpClient** class](https://api.dartlang.org/stable/2.1.0/dart-io/HttpClient-class.html)
    
* [**http** package on Pub](https://pub.dartlang.org/packages/http)
    
* [**Free Dart screencasts on Egghead.io**](https://egghead.io/instructors/jermaine-oppong)
