Chapter 16

  API呼び出し

heyhey1028
heyhey1028
2023.02.17に更新

この章ではアプリケーション開発で避けては通れない API 通信について解説していきます。

http パッケージ

Flutter から API 通信を行うにはhttpパッケージという外部パッケージを活用します。

https://pub.dev/packages/http

API 通信をサポートするパッケージでは他にもdioなど多機能で人気なパッケージがありますので、気になる方は試してみてください

パッケージの導入

  1. パッケージの追加
$ flutter pub add http
  1. 使用するファイルでimport
import 'package:http/http.dart' as http;

基本的な使い方

基本的な使い方をPUTメソッドを例に見ていきましょう

全体像
Future<Album> updateAlbum(String title) async {
  final response = await http.put(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
      HttpHeaders.authorizationHeader: 'Bearer $token',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );

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

エンドポイントの指定

全てのメソッドについて第一引数で Uri にパースしたエンドポイントの url を渡す必要があります。

Uri.parseメソッドに url のパスを指定するだけです。

Uri.parse('https://jsonplaceholder.typicode.com/albums/1')

header 要素の追加

メソッドのheaderパラメータに Map型で header 要素を渡すことが出来ます。'Content-Type'のように文字列で指定しても良いですし、httpパッケージでHttpHeadersというクラスによく使う文字列が定義されているのでそちらを使っても構いません。

authorization を必要とするような場合もこちらに追記し含めることが出来ます。

headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
    HttpHeaders.authorizationHeader: 'Bearer $token',
}

body 要素の追加

メソッドのbodyパラメータに更新するデータを渡す事で body 要素に追加する事ができます。

後述のjsonEncodeメソッドを使って、json 化した値を渡します。

body: jsonEncode(<String, String>{
    'title': title,
}),

レスポンスのハンドリング

レスポンスはhttpパッケージに定義されたResponse型として返却されます。statusCodeheadersbodyなどの情報が含められています。

これらの値を元にハンドリング処理を実装していきます。

if (response.statusCode == 200) {
    return response.body;
} else {
    throw Exception('Failed to update album.');
}

各種メソッド

基本的にはメソッド名が違うだけでその他の指定項目などは変わりません。

GET

Future<http.Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}

POST

Future<http.Response> createAlbum(String title) {
  return http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );
}

PUT

Future<http.Response> updateAlbum(String title) {
  return http.put(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );
}

PATCH

Future<http.Response> updateUserId(String userId) {
  return http.patch(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'userId': userId,
    }),
  );
}

DELETE

Future<http.Response> deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );

  return response;
}

まとめ

今回使ったhttpパッケージは機能はシンプルですが、記述もシンプルで使いやすかったかと思います。

さてここまで Flutter でアプリ開発を行うのに必要な知識は揃いました。次章よりこれまでに学んだ知識を使って実際にアプリを作ってみましょう!🚀