Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 61 ยท Real-World Dart

HTTP Clients and Servers

Call REST APIs with package:http, handle status codes and timeouts, and write small servers with dart:io HttpServer and shelf, with runnable stand-ins.

Dart is used for both sides of HTTP. Flutter apps and command-line tools call REST APIs, and Dart servers answer them. The language ships a low-level server and client in dart:io, and the community packages http (a friendly client) and shelf (a small server framework) cover most daily needs.

This lesson shows the real Dart code, which is read-only on this site because there is no Dart runtime and no network access from the code runners. To let you practice the same ideas, the TypeScript stand-ins start a tiny server on the loopback address and call it with fetch. You will need futures and async/await and JSON first.

Adding the http package

package:http is not part of the SDK. Add it to a project, then import it:

TEXT
dart pub add http
DART
import 'package:http/http.dart' as http;

The as http prefix is the convention, because names like get and post are too general to import bare. See libraries and packages for how imports and pubspec.yaml work.

A first GET request

DART
import 'dart:convert';
import 'package:http/http.dart' as http;

Future<void> main() async {
  final uri = Uri.https('api.example.com', '/users', {'page': '2'});
  final response = await http.get(uri);

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body) as List<dynamic>;
    print('Got ${data.length} users');
  } else {
    print('Request failed: ${response.statusCode}');
  }
}

Three habits are visible here:

  1. Build URLs with Uri, not string concatenation. Uri.https(host, path, queryParameters) encodes special characters for you. Uri.parse('https://...') works for fixed strings.
  2. Check statusCode. The http package does not throw for 404 or 500. A completed exchange is a successful Future, whatever the status. Only network problems (no connection, DNS failure) throw.
  3. Decode the body yourself. response.body is a String decoded using the charset from the headers. response.bodyBytes gives raw bytes.

Sending data

A POST with a JSON body needs the content type header and an encoded string:

DART
final response = await http.post(
  Uri.parse('https://api.example.com/users'),
  headers: {'Content-Type': 'application/json'},
  body: jsonEncode({'name': 'Ada', 'age': 36}),
);

if (response.statusCode == 201) {
  final created = jsonDecode(response.body) as Map<String, dynamic>;
  print('New id: ${created['id']}');
}

If you pass a Map as body instead of a string, http sends it as a form (application/x-www-form-urlencoded). That is a frequent surprise when an API expects JSON. http.put, http.patch and http.delete follow the same pattern.

Timeouts, errors and reuse

Network calls fail in several ways, and a good client plans for them. A request can hang, so add a timeout to the Future:

DART
import 'dart:async';
import 'dart:io';

Future<String> fetchName(http.Client client, int id) async {
  try {
    final response = await client
        .get(Uri.parse('https://api.example.com/users/$id'))
        .timeout(const Duration(seconds: 5));

    if (response.statusCode == 404) {
      throw StateError('No user with id $id');
    }
    if (response.statusCode != 200) {
      throw HttpException('Server answered ${response.statusCode}');
    }
    return (jsonDecode(response.body) as Map<String, dynamic>)['name'] as String;
  } on TimeoutException {
    throw StateError('The server took too long');
  } on SocketException {
    throw StateError('No network connection');
  }
}

Each failure kind gets its own on clause, as explained in exceptions. Convert low-level exceptions into errors your app understands, so callers do not need to know about sockets.

For several requests, create one http.Client, reuse it so connections stay open, and close it when finished:

DART
final client = http.Client();
try {
  final ids = [1, 2, 3];
  final names = await Future.wait(ids.map((id) => fetchName(client, id)));
  print(names);
} finally {
  client.close();
}

Future.wait sends all three requests at once. Without it, await in a loop would send them one after another.

sequenceDiagram
    participant App as Dart app
    participant API as Server
    App->>API: GET /users/1
    Note over App: .timeout(5 s)
    API-->>App: 200 + JSON body
    App->>App: jsonDecode and fromJson

A request is a Future. The timeout starts when you attach it; status checking and decoding happen after the response arrives.

TypeScript A local API and a client with a timeout (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A server with dart:io

The SDK includes HttpServer. It is a stream of requests, so you handle them with await for:

DART
import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8080);
  print('Listening on http://localhost:${server.port}');

  await for (final HttpRequest request in server) {
    if (request.method == 'GET' && request.uri.path == '/hello') {
      request.response
        ..statusCode = HttpStatus.ok
        ..headers.contentType = ContentType.json
        ..write(jsonEncode({'message': 'Hello'}));
    } else {
      request.response.statusCode = HttpStatus.notFound;
    }
    await request.response.close();
  }
}

The response is written like a sink, with cascades for compactness. Nothing is sent until you close() it. Binding to loopbackIPv4 accepts only local connections; use InternetAddress.anyIPv4 when the server must be reachable from other machines.

This works, but routing by hand with if chains gets tiring. That is where shelf helps.

Servers with shelf

shelf models a server as two simple ideas:

  • A handler is a function from Request to Response (or a Future of one).
  • Middleware wraps a handler to add behavior, such as logging or authentication.
DART
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;

Response _hello(Request request) =>
    Response.ok('{"message":"Hello"}', headers: {'content-type': 'application/json'});

Future<void> main() async {
  final handler = const Pipeline()
      .addMiddleware(logRequests())
      .addHandler((request) {
    if (request.method == 'GET' && request.url.path == 'hello') {
      return _hello(request);
    }
    return Response.notFound('Not found');
  });

  final server = await io.serve(handler, 'localhost', 8080);
  print('Serving on http://${server.address.host}:${server.port}');
}

Because handlers are plain functions, you can test them by calling them directly with a Request(...), without opening a socket. The companion package shelf_router adds path templates such as /users/<id>. Frameworks such as Dart Frog and Serverpod build on the same foundations when you need more structure.

TypeScript Handlers and middleware as functions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Practical advice

  • Never trust the network. Servers send errors, partial data and surprise fields. Validate JSON in fromJson and map status codes to meaningful errors.
  • Always set a timeout on calls the user is waiting for, and decide whether retrying makes sense. Retry only operations that are safe to repeat (GET, or PUT with the same body), and wait longer after each failure.
  • Keep secrets out of the code. Tokens belong in environment variables or secure storage, never in the repository.
  • Prefer HTTPS. On Android and iOS, plain HTTP is blocked by default for good reasons.
  • Do not block the UI. Network calls are asynchronous, so await them; decoding a very large response can be moved to a worker with an isolate.
  • Use dart:io HttpClient only when you need low-level control. The http package covers the common cases and also works on the web, where dart:io does not exist.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A server answers 404 Not Found. What does await http.get(uri) do?

    The http package treats any completed exchange as a successful Future. Only network failures throw, so status codes must be checked.
  2. 2. What happens if you pass a Map as body to http.post?

    A Map body is form-encoded. To send JSON, call jsonEncode and set the Content-Type header.
  3. 3. How do you stop a request from waiting forever?

    Future.timeout completes with a TimeoutException (or a fallback value) when the time limit passes.
  4. 4. In shelf, what is a middleware?

    A handler maps Request to Response. Middleware takes a handler and returns a new handler, so you can stack features in a Pipeline.

Summary

  • package:http offers get, post, put, patch and delete; build URLs with Uri, check statusCode and decode the body with jsonDecode.
  • Send JSON by encoding it yourself and setting Content-Type; a Map body means a form.
  • Add .timeout(...), catch TimeoutException and SocketException, and reuse and close one http.Client.
  • dart:io HttpServer gives a stream of requests; shelf models servers as handlers plus middleware.
  • Handlers are plain functions, so they are easy to test without a network.

Next: testing with package:test.