1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】HTTPを用いてAPIリクエスト実装した

1
Posted at

はじめに

APIを利用することで、アプリ開発の可能性は大きく広がります。Flutterでは、httpパッケージを利用することでHTTP通信を簡単に実装できます。今回はOpenWeatherMap APIを使って、特定地域の天気情報を取得するアプリを作りました。とても簡単に実装できたので共有したいと思います。

開発環境

  • Flutter: 3.14.0
  • Dart: 3.2.0

パッケージのインストール

httpというパッケージを利用します。

  http: ^1.1.0

APIへのリクエスト

http.get()メソッドを使用してOpenWeatherMap APIのAPIエンドポイントにGETリクエストを送信します。この例では、石川県(緯度: 26, 経度: 128)の天気情報をリクエストしています。YourAPIKeyにはOpenWeatherMapで取得したAPIKeyを各自記入してください。

const apiKey = 'YourAPIKey'; // 各自APIKeyを記述
  var url = Uri.https(
      // ホスト
      'api.openweathermap.org',
      // パス
      '/data/2.5/weather',
      {
        // クエリパラメータ(石川のLatLongを使用)
        'lat': '26',
        'lon': '128',
        'appid': apiKey,
      });

  var response = await http.get(url);

レスポンスの処理

リクエストが成功した場合(statusCode:200)、レスポンスのbodyがJSON形式で返されます。これをデコードし、欲しいデータを抽出することができます。

以下のコードでは成功したリクエストの天気情報をコンソールに出力しています。リクエストが失敗した場合は、ステータスコードと共にエラーメッセージが表示されます。

var response = await http.get(url);
if (response.statusCode == 200) {
  var jsonResponse = convert.jsonDecode(response.body) as Map<String, dynamic>;
  print("✅ 天気: ${jsonResponse['weather'][0]['main']}");
} else {
  print('❌ Request failed with status: ${response.statusCode}.');
}

出力例(成功した場合)

✅ 天気: Clouds

コード全文

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

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

void main(List<String> arguments) async {
  const apiKey = 'YourAPIKey';
  var url = Uri.https(
      // ホスト
      'api.openweathermap.org',
      // パス
      '/data/2.5/weather',
      {
        // クエリパラメータ(石川のLatLongを使用)
        'lat': '26',
        'lon': '128',
        'appid': apiKey,
      });

  var response = await http.get(url);
  if (response.statusCode == 200) {
    var jsonResponse =
        convert.jsonDecode(response.body) as Map<String, dynamic>;
    print("✅ 天気: ${jsonResponse['weather'][0]['main']}");
  } else {
    print('❌ Request failed with status: ${response.statusCode}.');
  }
}

最後に

本記事では、Flutterで外部APIへのHTTPリクエストを送信し、レスポンスデータを処理する基本的な方法を紹介しました。HTTPリクエストの送信方法をマスターすることで、バックエンドとの連携など、より高度な開発が可能になります。これからも、この技術を活用して面白い開発を進めていきたいと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?