Quick tip: How to make HTTP requests (Dart)
Tags: dart, http, beginners, tips
Published: 2018-08-02 08:37:55

---
title: Quick tip: How to make HTTP requests (Dart)
published: true
description: Learn how you could make requests to resources in Dart
tags: dart, http, beginners, tips
cover_image: https://thepracticaldev.s3.amazonaws.com/i/xuccl2iebiyg19gu7x0w.png
canonical_url: https://creativebracket.com/quick-tip-how-to-make-http-requests/
---

It's quite common to build web applications that pull in data from other web applications, initiated by logic that performs HTTP calls to third party services.

In today's quick tip, we will look at how we can use the inbuilt `HttpClient` and `HttpRequest` classes to make HTTP calls to external services. These classes are used on the server and client respectively.

---

## On the server

Dart provides the `HttpClient` class in the **dart:io** library for making HTTP calls. Here's an example of it in action:

```dart
import 'dart:io';
import 'dart:convert';

void main() {
  HttpClient()
    .getUrl(Uri.parse('https://swapi.co/api/people/1')) // produces a request object
    .then((request) => request.close()) // sends the request
    .then((response) => response.transform(Utf8Decoder()).listen(print)); // transforms and prints the response
}
```
Running this file will give you the JSON response below:

```json
{"name":"Luke Skywalker","height":"172","mass":"77","hair_color":"blond","skin_color":"fair","eye_color":"blue","birth_year":"19BBY","gender":"male","homeworld":"https://swapi.co/api/planets/1/","films":["https://swapi.co/api/films/2/","https://swapi.co/api/films/6/","https://swapi.co/api/films/3/","https://swapi.co/api/films/1/","https://swapi.co/api/films/7/"],"species":["https://swapi.co/api/species/1/"],"vehicles":["https://swapi.co/api/vehicles/14/","https://swapi.co/api/vehicles/30/"],"starships":["https://swapi.co/api/starships/12/","https://swapi.co/api/starships/22/"],"created":"2014-12-09T13:50:51.644000Z","edited":"2014-12-20T21:17:56.891000Z","url":"https://swapi.co/api/people/1/"}
```
And then there's the prettier **async/await** version:

```dart
import 'dart:io';
import 'dart:convert';

void main() async {
  var request = await HttpClient().getUrl(Uri.parse('https://swapi.co/api/people/1')); // produces a request object
  var response = await request.close(); // sends the request

  // transforms and prints the response
  await for (var contents in response.transform(Utf8Decoder())) {
    print(contents);
  }
}
```

Here's a video I made earlier:

{% youtube Sz2JbmRKxY8 %}

## On the client

Dart provides the `HttpRequest` class in the **dart:html** library:

```dart
import 'dart:html';

void main() {
  HttpRequest.getString('https://swapi.co/api/people/1')
    .then(print);
}
```
And with **async/await**:

```dart
import 'dart:html';

void main() async {
  print(await HttpRequest.getString('https://swapi.co/api/people/1'));
}
```

Try this snippet on [DartPad](https://dartpad.dartlang.org).


## UPDATE: 06-10-2018

_On of my Medium readers wondered how to make POST requests on the client. Thought it useful to have my answer here too:_

You can make a POST request by using the `postFormData` static method:

```dart
var data = { 'firstName' : 'John', 'lastName' : 'Doe' };
HttpRequest.postFormData('/send', data).then((HttpRequest resp) {
  // Do something with the response.
});
```

The `Content-Type` header will be set to `Content-Type: application/x-www-form-urlencoded; charset=UTF-8` by default, unless you want the payload to be treated as a JSON object:

```dart
import 'dart:html';
import 'dart:convert';

void main() {
  var data = { 'title' : 'My first post' };
  HttpRequest.request(
    'https://jsonplaceholder.typicode.com/posts',
    method: 'POST',
    sendData: json.encode(data),
    requestHeaders: {
      'Content-Type': 'application/json; charset=UTF-8'
    }
  )
  .then((resp) {
    print(resp.responseUrl);
    print(resp.responseText);           
  });
}

// Response
// https://jsonplaceholder.typicode.com/posts
// { "title": "My first post", "id": "101" }
```

Try this snippet on [DartPad](https://dartpad.dartlang.org).

To offer a uniform solution for client and serverside requests, the Dart team have created the excellent [HTTP package](https://pub.dartlang.org/packages/http), now available on Pub.

---

And that's it for today's quick tip. Check out the documentation links below to learn how you could perform other types of requests.

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

## Learn more

1. [HttpClient class](https://api.dartlang.org/stable/2.0.0/dart-io/HttpClient-class.html)
2. [HttpRequest class](https://api.dartlang.org/stable/2.0.0/dart-html/HttpRequest-class.html)
3. [Fetching Data Dynamically - clientside](https://webdev.dartlang.org/tutorials/get-data/fetch-data)



_**Lastly**...I want to thank you all for the positive feedback on my "Darticles"_🤓. _I've had increasing support_ ⭐ _which really means a lot and I'm very glad to see growth in the Dart community due to innovations like_ [Flutter](https://flutter.io) _and_ [Aqueduct](https://aqueduct.io).