Creative Bracket

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:

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:

{"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:

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:

On the client

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

import 'dart:html';

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

And with async/await:

import 'dart:html';

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

Try this snippet on DartPad.

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:

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:

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.

To offer a uniform solution for client and serverside requests, the Dart team have created the excellent HTTP package, 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
  2. HttpRequest class
  3. Fetching Data Dynamically – clientside

Lastly…I want to thank you all for the positive feedback on my “Darticles”. I’ve had increasing supportwhich really means a lot and I’m very glad to see growth in the Dart community due to innovations like Flutter and Aqueduct.

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.