Day 16: Fetching Data from the Internet: REST APIs with http

Day-16-Fetching-Data-from-the-Internet-REST-APIs-with-http.jpg
Day 16: Fetching API Data | 30-Day Flutter Blog

Day 16: Talking to the Internet

Your app is no longer an island. Today, we’ll build bridges to the outside world by fetching live data from the internet using REST APIs and the `http` package.

The What & Why: Understanding APIs

API stands for Application Programming Interface. That sounds complicated, but the concept is simple. Think of it like a restaurant menu.

You (the client, your app) don’t know how to cook the food (the data). The kitchen (the server) does. The menu (the API) provides a list of specific dishes you can order (requests). You tell the waiter what you want, they take your order to the kitchen, and bring back your food (the response). You don’t need to know the recipe; you just need to know how to order from the menu.

The How: Making GET Requests

A `GET` request is the most common type. It’s simply asking a server to “get” some data for you. To do this in Flutter, we use the excellent `http` package. First, you’d add it to your `pubspec.yaml` file:

dependencies:
  http: ^1.2.1

Live Simulation: Fetching a Blog Post

The Code:

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

Future<Post> fetchPost() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/posts/1')
  );

  if (response.statusCode == 200) {
    // If the server returns a 200 OK response,
    // then parse the JSON.
    return Post.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK,
    // then throw an exception.
    throw Exception('Failed to load post');
  }
}

The Result:

Click the button to fetch data from a live API.

Sending Data Back: Making POST Requests

What if you want to send data *to* the server, like creating a new user or submitting a new blog post? For that, we use a `POST` request. Instead of just asking for data, we package up our own data (usually as a JSON string) and include it in the “body” of our request.

Live Simulation: Creating a New Post

The Form:

The Result:

Fill out the form and click “Create Post” to send the data to the server.

Share