Menghubungkan Android ke REST API
Mahasiswa mampu:
Ojek online, marketplace, media sosial, absensi kampus β semuanya mengambil data dari server.
Aplikasi mengambil dan mengirim data tersebut melalui API.
Membuat aplikasi CRUD lengkap yang terhubung ke server melalui internet.
Ambil data dari API, tampilkan, dan kirim data kembali.
Kamu (aplikasi) β pelayan (API) β dapur (server). Kamu tidak masuk dapur, kamu memesan lewat pelayan.
Komunikasi berbasis teks standar: server yang sama bisa dipakai Android, iOS, dan Web.
Semua adalah resource dengan URL (endpoint). Aksi ditentukan oleh HTTP method, bukan URL.
| Aksi | Method | Endpoint |
|---|---|---|
| Ambil semua post | GET | /posts |
| Ambil satu post | GET | /posts/{id} |
| Buat post baru | POST | /posts |
| Ganti seluruh isi post | PUT | /posts/{id} |
| Ganti sebagian isi post | PATCH | /posts/{id} |
| Hapus post | DELETE | /posts/{id} |
β¦/api/v2/posts/1Content-Type: application/json2xx sukses Β· 4xx salah client Β· 5xx salah server β di Retrofit, 4xx/5xx ditangkap sebagai HttpException
Data di server
Field yang tidak dikirim tetap utuh.
Field yang tidak dikirim hilang / dikosongkan.
{
"title": "Judul postingan",
"body": "Isi postingan",
"id": "1"
}
data class Post(
val id: String,
val title: String,
val body: String
)data class PostRequest(
val title: String? = null,
val body: String? = null
)Post = model respons Β· PostRequest = model requestnull tidak ikut dikirim β inilah yang membuat PATCH bisa mengubah sebagian data sajaAPI client open source, offline-first, collection berupa file teks .bru (mudah dibagikan lewat Git). Alternatif: Postman, Insomnia, curl.
Pertemuan11id barubody tetap utuhREST API palsu tapi benar-benar berfungsi β tanpa menulis backend.
| JSONPlaceholder | MockAPI.io | |
|---|---|---|
| Setup | langsung pakai | akun + resource |
| Data | statis, tidak disimpan | CRUD tersimpan |
| Cocok untuk | demo GET cepat | praktik CRUD penuh |
poststitle, body (string) β Generatehttps://<kunci>.mockapi.io/api/v2/id di MockAPI bertipe String, bukan angka β val id: String. POST β 201, PUT/PATCH β 200, DELETE β 200 lalu GET β 404.Post)Penerjemah yang mengubah teks JSON menjadi objek Kotlin yang mudah dipakai.Post dipasang ke daftar sehingga datanya muncul di layar pengguna.data/model/ β Post, PostRequestdata/api/ β ApiService, RetrofitClientroot β Activity & Adapter
interface ApiService {
@GET("posts")
suspend fun getPosts(): List<Post>
@GET("posts/{id}")
suspend fun getPostById(@Path("id") id: String): Post
@POST("posts")
suspend fun createPost(@Body request: PostRequest): Response<Post>
@PUT("posts/{id}")
suspend fun updatePost(@Path("id") id: String,
@Body request: PostRequest): Response<Post>
@PATCH("posts/{id}")
suspend fun patchPost(@Path("id") id: String,
@Body request: PostRequest): Response<Post>
@DELETE("posts/{id}")
suspend fun deletePost(@Path("id") id: String): Response<ResponseBody>
}
@Path menyisipkan nilai ke path; @Body dijadikan JSON.Post / List<Post> β kita hanya mendapat datanya. Dipakai di GET.Response<Post> β kita mendapat data + status code (200, 201, β¦). Dipakai di POST, PUT, PATCH.Response<ResponseBody> β balasannya hanya teks mentah data yang terhapus, jadi tidak diubah menjadi objek Post.object RetrofitClient {
private const val BASE_URL =
"https://<kunci>.mockapi.io/api/v2/"
private val loggingInterceptor =
HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG)
Level.BODY else Level.NONE
}
private val okHttpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor).build()
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService: ApiService =
retrofit.create(ApiService::class.java)
}
object = singleton, dipakai semua activitybaseUrl wajib diakhiri β/β β kesalahan klasikGsonConverterFactory = jembatan JSON β KotlinHttpLoggingInterceptor cetak request/response ke LogcatINTERNETβ Request di main thread
β Dengan coroutine
lifecycleScope.launch, fungsi tidak berjalan.lifecycleScope.launch {
try {
val posts = RetrofitClient
.apiService.getPosts()
postAdapter.updateData(posts)
} catch (e: IOException) {
// tidak ada internet
} catch (e: HttpException) {
// 4xx / 5xx
}
}
suspend boleh βdijedaβ tanpa memblokir UIgetCount, getItem, getItemId, getView. convertView + tag = memakai kembali tampilan baris yang sudah ada saat daftar digulir, agar hemat memori. notifyDataSetChanged() = memberi tahu ListView bahwa data berubah, supaya tampilannya diperbarui.
Intent(this, PostDetailActivity::class.java)putExtra(EXTRA_POST_ID, id) β getStringExtra(). Muat ulang di onResume().
viewBinding = true β ActivityMainBinding dsb. Akses view tanpa findViewById, dicek compiler.
GET semua post β ListView; tombol ke form POST
GET satu post; tombol PUT, PATCH (dialog), DELETE
Satu activity dua mode: CREATE (POST) & EDIT (PUT)
Konfirmasi tiap aksi: dialog berisi status code + JSON respons (Gson pretty-print).
00:00β00:20 | Teori API, clientβserver, REST & HTTP |
00:20β00:35 | JSON + model Kotlin |
00:35β01:00 | Demo Bruno ke MockAPI (GET/POST/PUT/PATCH/DELETE) |
01:00β01:45 | Praktik Tahap 0β2: konfigurasi, lapisan data, GET list |
01:55β02:25 | Praktik Tahap 3β4: detail + form POST (setelah istirahat 10β) |
02:25β02:50 | Praktik Tahap 5β6: PUT, PATCH, DELETE + uji CRUD penuh |
02:50β03:00 | Debugging umum, QA, penutup + tugas |
Demo Bruno membuktikan bedanya di JSON.
Crash saat build.
Muncul UnknownHostException.
id dikira angkaDi MockAPI bertipe String.
suspend = ajaibTanpa lifecycleScope.launch tidak berjalan.
Data jadi null / diabaikan diam-diam.
object)square.github.io/retrofit
github.com/google/gson
mockapi.io Β· usebruno.com
developer.mozilla.org β HTTP/Status
jsonplaceholder.typicode.com
developer.android.com/kotlin/coroutines
Ada pertanyaan?