[Flutter] How to use http to call API

2023-03-18 hit count image

Let's see how to use the http package to call the server API in Flutter.

Outline

In this blog post, I will introduce how to use the http package to call the server API in Flutter.

You can see the full source code of this blog post in the following link.

Install http

To check how to use the http package in Flutter, execute the following command to create a new Flutter project.

flutter create http_example

And then, execute the following command to install the http package.

flutter pub add http

Next, let’s see how to use the http package.

How to use

You can use the http package to call the GET/POST method of the server API like the below.

  • get
import 'package:http/http.dart' as http;

final url = Uri.parse('https://reqbin.com/sample/post/json');
final response = await http.post(url, body: {
  'key': 'value',
});

print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
  • post
import 'package:http/http.dart' as http;

final url = Uri.parse(
  'https://raw.githubusercontent.com/dev-yakuza/users/master/api.json',
);
final response = await http.get(url);

print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');

Example

To check how to use the http package, open the lib/main.dart file and modify it like the below.

// ignore_for_file: avoid_print

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  void _callAPI() async {
    var url = Uri.parse(
      'https://raw.githubusercontent.com/dev-yakuza/users/master/api.json',
    );
    var response = await http.get(url);
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');

    url = Uri.parse('https://reqbin.com/sample/post/json');
    response = await http.post(url, body: {
      'key': 'value',
    });
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('http Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _callAPI,
          child: const Text('Call API'),
        ),
      ),
    );
  }
}

When you run the above code, you can see the Call API button on the center of the screen like the below.

Flutter - http example

And, when you press the button, you can see the API is called by the http package.

void _callAPI() async {
  var url = Uri.parse(
    'https://raw.githubusercontent.com/dev-yakuza/users/master/api.json',
  );
  var response = await http.get(url);
  print('Response status: ${response.statusCode}');
  print('Response body: ${response.body}');

  url = Uri.parse('https://reqbin.com/sample/post/json');
  response = await http.post(url, body: {
    'key': 'value',
  });
  print('Response status: ${response.statusCode}');
  print('Response body: ${response.body}');
}

If the API is called successfully by the http package, you can see the following result on the Debug console.

flutter: Response status: 200
flutter: Response body: [
  {
    "name": "Durand Thomas",
    "photo": "https://raw.githubusercontent.com/dev-yakuza/users/master/images/1.jpg"
  },
  {
    "name": "Petersen Simon",
    "photo": "https://raw.githubusercontent.com/dev-yakuza/users/master/images/5.jpg"
  },
  {
    "name": "Øglænd Helene",
    "photo": "https://raw.githubusercontent.com/dev-yakuza/users/master/images/6.jpg"
  },
  {
    "name": "Jean Olivia",
    "photo": "https://raw.githubusercontent.com/dev-yakuza/users/master/images/7.jpg"
  },
  {
    "name": "Owren Aras",
    "photo": "https://raw.githubusercontent.com/dev-yakuza/users/master/images/8.<…>
flutter: Response status: 200
flutter: Response body: {"success":"true"}

Completed

Done! we’ve seen how to use the http package to call the API in Flutter. Now, try to use the http package to communicate with the server API.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts