DEV Community

Cover image for Quick tip: How to make HTTP requests (Dart)
Jermaine
Jermaine

Posted on • Updated on • Originally published at creativebracket.com

Quick tip: How to make HTTP requests (Dart)

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
}
Enter fullscreen mode Exit fullscreen mode

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/"}
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

And with async/await:

import 'dart:html';

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

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.
});
Enter fullscreen mode Exit fullscreen mode

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" }
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (6)

Collapse
 
teknohipy profile image
teknohipy

Thanks for this. Followed!
Which IDE do you use?

I'm having trouble getting your HttpRequest.getString to work on an actual web app... works fine on DartPad, but not in an IDE. I use WebStorm (seems to be most popular / supported.)
I've gotten basic apps working with both webstorm templates 'bare bones web app' & 'console application'. But following similar steps, pasting your code, running, returns empty browser tabs. and no console printout. (What makes it 'just work' in a DartPad?)

Many thanks for any insight... I'm a Swift dev, an Xcode guy, and brand-new to web development:)

Collapse
 
creativ_bracket profile image
Jermaine

Hey @teknohipy , I use Visual Studio Code with this extension. Also, I've launched a new blog at creativebracket.com. Do check it out for more tutorials :)

Collapse
 
teknohipy profile image
teknohipy

Thanks man, i'll try it out. Will check out your blog too.

IDE choices aside though... what else is needed to build your code into an actual working program?

(like i asked "What makes it 'just work' in a DartPad?")

It seems, "DartPad" just gives console printouts, for those who don't have an IDE... but, unless your code actually runs in an IDE, producing output (ie console printouts) can you really call it a working program!

Thread Thread
 
creativ_bracket profile image
Jermaine

what else is needed to build your code into an actual working program?

The webdev tool by the Dart team handles serving and bundling web-based projects. It works out-the-box with the project structure below:

web
  style.css
  main.dart
  index.html
pubspec.yaml

It would be a good idea to look at stagehand by the Dart team. It generates the scaffolding for a project including the necessary packages. I've got some video tutorials on my YouTube channel going through this.

Collapse
 
nguyenquangtin profile image
Tony Tin Nguyen

Thanks for the useful guide.

Collapse
 
mohamad_el_bohsaly profile image
Mohamad El Bohsaly

How to call multiple http post calls? Package http