japan_post_api_client 1.0.3 copy "japan_post_api_client: ^1.0.3" to clipboard
japan_post_api_client: ^1.0.3 copied to clipboard

A Flutter client for the Japan Post API, simplifying integration of postal code and address search functionalities into your applications with robust token management and error handling.

English | 日本語

japan_post_api_client #

pub package style: effective dart Platform Badge License: MIT

A Flutter client for the Japan Post API (https://lp-api.da.pf.japanpost.jp/). This package simplifies interaction with Japan Post services, making it incredibly straightforward to integrate postal code and address search functionalities into your Flutter applications.

日本郵便API(https://lp-api.da.pf.japanpost.jp/) のFlutterクライアントです。 このパッケージは日本郵便サービスとの連携を簡素化し、郵便番号や住所検索機能をFlutterアプリケーションに非常に簡単に統合できるようにします。

demo!

Features #

  • Postal Code Search: Easily search for addresses using a Japanese postal code.
  • Address Detail Search: Search for addresses by providing prefecture, city, and town names.
  • API Token Management: Handles API token acquisition and management for seamless integration.
  • Error Handling: Provides clear error handling for API responses.

Getting started #

  1. Add to pubspec.yaml: Add the japan_post_api_client to your project's pubspec.yaml file:

    dependencies:
      japan_post_api_client: ^0.0.1 # Use the latest version
      public_ip_address: ^1.2.0 # As an example, we use this package to get public ip address on running device. You can use your favorite package.
    
  2. Install dependencies: Run flutter pub get in your project's root directory.

Simple example (Dart cli) #

import 'dart:io';

import 'package:japan_post_api_client/japan_post_api_client.dart';
import 'package:public_ip_address/public_ip_address.dart';

Future<void> main() async {
  final client = JapanPostApiClient(
    clientId: 'YOUR_CLIENT_ID',
    secretKey: 'YOUR_SECRET_KEY',
  );

  final ipAddress = await (IpAddress().getIp());
  await client.getToken(ipAddress);
  final result = await client.searchByPostalCode('1000001');

  switch (result) {
    case ApiResultOk(data: SearchcodeSearchRes(addresses: final data)):
      for (final address in data) {
        print('$data');
      }
    case ApiResultError(error: final e, stackTrace: final s):
      print('Error: $e, $s');
    default:
      print('something went wrong');
  }

  exit(0);
}
# output should be like below
SearchcodeSearchResAddressesInner[dgacode=null, zipCode=null, prefCode=13, prefName=東京都, prefKana=トウキョウト, prefRoma=TOKYO, cityCode=null, cityName=千代田区, cityKana=チヨダク, cityRoma=CHIYODA-KU, townName=千代田, townKana=チヨダ, townRoma=CHIYODA, bizName=null, bizKana=null, bizRoma=null, blockName=null, otherName=null, address=null, longitude=null, latitude=null]

Usage #

Initialize the API Client #

Initialize the JapanPostApiClient with your client ID and secret key. You will also need to obtain an API token using your public IP address. The getToken method handles this process.

import 'package:japan_post_api_client/japan_post_api_client.dart';
import 'package:public_ip_address/public_ip_address.dart';

// Replace with your actual client ID and secret key
final apiClient = JapanPostApiClient(
    clientId: 'YOUR_CLIENT_ID',
    secretKey: 'YOUR_SECRET_KEY',
);

Future<void> initializeApiClient(String publicIp) async {

  final result = await apiClient.getToken(publicIp);
  switch (result) {
    case ApiResultOk():
      // API Client initialized and token obtained.
      // TODO: Update UI state to indicate successful initialization
      // For example: setState(() { _isApiClientInitialized = true; });
      break;
    case ApiResultError(error: final e, stackTrace: final s):
      // TODO: Handle initialization error, e.g., show a SnackBar or dialog
      // print('Error initializing API Client or getting token: $e');
      break;
  }
}

Obtaining Public IP Address (Example)

The Japan Post API requires your public IP address for token acquisition. You can obtain this programmatically using packages like public_ip_address.

First, add the dependency to your pubspec.yaml:

dependencies:
  public_ip_address: ^latest_version # Use the latest version

Then, you can get the IP address like this:

import 'package:public_ip_address/public_ip_address.dart';

Future<String?> getPublicIp() async {
  final ipChecker = IpAddress();
  try {
    final ipAddress = await ipChecker.getIp();
    return ipAddress;
  } catch (e) {
    // Handle error, e.g., log it or show a message
    return null;
  }
}

You would then pass the result of getPublicIp() to the initializeApiClient function.

To search for an address using a postal code:

import 'package:japan_post_api_client/japan_post_api_client.dart';

Future<List<SearchcodeSearchResAddressesInner>> searchByPostalCode(String postalCode) async {
  final result = await apiClient.searchByPostalCode(postalCode);
  switch (result) {
    case ApiResultOk(data: SearchcodeSearchRes(addresses: final data)):
        return data;
    case ApiResultError(error: final e, stackTrace: final s):
      // TODO: Handle search error, e.g., show a SnackBar or dialog
      // print('Error searching by postal code: $e');
      return [];
    default: 
      return [];
  }
}

To search for an address using prefecture, city, and town names:

import 'package:japan_post_api_client/japan_post_api_client.dart';
import 'package:japan_post_api_client/src/model/address_req.dart';

Future<List<AddressResAddressesInner>> searchByAddressDetails(String prefName, String cityName, String townName) async {
  final addressReq = AddressReq(
    prefName: prefName,
    cityName: cityName,
    townName: townName,
  );
  final result = await apiClient.searchByAddress(addressReq);
  switch (result) {
    case ApiResultOk(data: AddressRes(addresses: final data)):
        return data;
    case ApiResultError(error: final e, stackTrace: final s):
      // TODO: Handle search error, e.g., show a SnackBar or dialog
      // print('Error searching by address details: $e');
      return [];
    default: 
      return [];
  }
}

For a complete, runnable example, please refer to the example/ directory in this repository.

Direct API Access #

For more granular control or to access specific API endpoints directly, you can use the apiClient.searchcodeApi and apiClient.addresszipApi fields after successful token initialization. These fields expose the underlying API client objects, allowing you to call their methods with all available parameters.

Example: Using searchcodeApi directly

import 'package:japan_post_api_client/japan_post_api_client.dart';

Future<List<SearchcodeSearchResAddressesInner>> directSearchCode(
  String postalCode, {
  num? page,
  num? limit,
  String? ecUid,
  num? choikitype,
  num? searchtype,
}) async {

  final SearchcodeApi? searchcodeApi = apiClient.searchcodeApi;

  if (searchcodeApi == null) {
    // Handle case where searchcodeApi is not initialized (e.g., token not obtained)
    return [];
  }

  try {
    final searchcodeRes = await searchcodeApi.searchCode(
      postalCode,
      limit: limit,
      searchtype: searchtype,
      page: page,
      choikitype: choikitype,
    );

    if (searchcodeRes != null && searchcodeRes.addresses.isNotEmpty) {
      // TODO: Process and display the addresses
      return searchcodeRes.addresses;
    } else {
      // TODO: Handle no address found
      return [];
    }
  } catch (e) {
    // TODO: Handle API error
    return [];
  }
}
0
likes
150
points
50
downloads

Publisher

verified publishersatoyan.net

Weekly Downloads

A Flutter client for the Japan Post API, simplifying integration of postal code and address search functionalities into your applications with robust token management and error handling.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (license)

Dependencies

collection, flutter, http

More

Packages that depend on japan_post_api_client