10
10

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 5 years have passed since last update.

Retrofitを使ってSORACOM APIを呼び出すライブラリを作ってみた

Posted at

SORACOM APIを使えばSORACOMのサービスをプログラム内でコントロールする事ができます。今回はSquare社製のOSSライブラリ「Retrofit」を使ってAndroidからSORACOM APIを呼び出すプログラムを作ってみました。

SORACOM API
https://dev.soracom.io/jp/docs/api/

Retrofit (今回は2.0.0-beta2を使用)
http://square.github.io/retrofit/

RetrofitでAPI呼び出し部分をどうやって書いたか

Retrofitを使えば以下のように書くだけで呼び出し部分が完成します。ここではauthAPIを呼び出す部分だけ書いてみます。

SORACOMのauthAPIをRetrofitで実装した例
public class Soracom {

    public static final Api API;

    static {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.soracom.io/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        API = retrofit.create(Api.class);
    }    

    public interface Api {

        @POST("auth")
        Call<AuthInfo> auth(@Body AuthRequest authRequest);
    }
}

Request用、Response用のモデルクラスを作ったのち、Apiインターフェイスを上記のように書くだけで呼び出しインターフェイス部分はOKです。
初期化の部分はstaticブロック内で全て完結しています。SORACOM APIのレスポンスのフォーマットは全てJSONなのでJSONパーサであるCsonConverterFactoryを使います。ちなみに、このパーサは内部でGsonを使っているのでモデルクラスもそれに対応した形で作っていきます。

作ったAPIをどのように呼び出すか?

ワーカースレッド内で以下のように呼び出すだけでOKです。

API呼び出し例
Call<AuthInfo> call = Soracom.API.auth(new AuthRequest(email, password));
Response<AuthInfo> response = call.execute();
AuthInfo authInfo = response.body();

Call<?>はRetrofitのクラスなのでenqueueメソッドを使えばUIスレッドから呼び出しすことができます。(このメソッドを呼ぶことでAPI問い合わせの処理を非同期呼び出しています。)

enqueueメソッドを使った例
Call<AuthInfo> call = Soracom.API.auth(new AuthRequest(email, password));
call.enqueue(new Callback<AuthInfo> (){
    @Override
    public void onResponse(Response<AuthInfo> response, Retrofit retrofit) {
        AuthInfo authInfo = response.body();
    }

    @Override
    public void onFailure(Throwable t) {
    }
});

そのライブラリ、使えます。

Retrofitを使えばAndroidで簡単にSORACOM APIを呼び出すことができます。そして、このAPIを実装したライブラリを用意しました。ApacheLicense2.0で公開しています。

SoracomApiAndroid
https://github.com/LyricalMaestro/SoracomApiAndroid

まだまだ不完全なところがありますが少しずつパワーアップさせていきます。(プルリクトかも受け付けます)
ライブラリはbuild.gradleのdependenceブロック内にcom.lyricaloriginal:soracom-api-android:+と記載すれば使うことができます。

build.gradle
    //中略

dependencies {
    
    //中略

    compile 'com.lyricaloriginal:soracom-api-android:+'
}

これを使ったアプリもあります。ぜひ動かしてみてください。

SoracomSampleApp
https://github.com/LyricalMaestro/SoracomSampleApp

10
10
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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?