Androidアプリでサーバーと通信するとき、定番のライブラリといえば Retrofit
ですね。
シンプルに導入できて、コードもスッキリ書けるので個人開発から実務まで幅広く使われています。
今回は、Retrofitを使ってシンプルなAPI通信を行う方法をまとめてみます。
Retrofitの導入
まずはGradleに依存関係を追加します。
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
これでRetrofit本体と、GsonによるJSON変換が使えるようになります。
APIインターフェースの定義
Retrofitでは、まずAPIのエンドポイントをインターフェースとして定義します。
interface ApiService {
@GET("users")
suspend fun getUsers(): List<User>
}
上記の例では、/users
にアクセスして User
のリストを取得する想定です。
データクラスの定義
次に、受け取るJSONをマッピングするためのデータクラスを作成します。
data class User(
val id: Int,
val name: String,
val email: String
)
Gsonが自動的にJSONをこのデータクラスへ変換してくれます。
Retrofitインスタンスの作成
次に、Retrofitのインスタンスを作成します。
object ApiClient {
private const val BASE_URL = "https://example.com/api/"
val instance: ApiService by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(ApiService::class.java)
}
}
lazy
を使うことで、最初に呼び出されたときにインスタンスが生成されます。
実際に呼び出す
最後に、ActivityやViewModelなどからAPIを呼び出してみます。
class MainViewModel : ViewModel() {
private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>> = _users
fun fetchUsers() {
viewModelScope.launch {
try {
val result = ApiClient.instance.getUsers()
_users.value = result
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
これで非同期でユーザー一覧を取得し、LiveDataに反映することができます。
まとめ
Retrofitを使えば、API通信がとてもシンプルに書けるようになります。
特に Coroutine + Retrofit
の組み合わせは現代的で、実務でもよく使われるパターンですね。
👉 最初は小さなAPIから試してみて、慣れてきたらInterceptorやOkHttpと組み合わせて拡張していくのがおすすめです。
コメント