본문 바로가기

앱 개발/Kotlin_Android

API 사용하여 동영상 가져오기

1) Retrofit 설정
Retrofit은 Android를 위한 타입 safety HTTP 클라이언트 라이브러리이다.

build.gradle (Module: app)
dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
}


2) API 인터페이스 정의
Retrofit 인터페이스를 정의하여 API 엔드포인트와 상호작용한다.

interface ApiService {
    @GET("search")
    suspend fun searchVideos(
        @Query("part") part: String,
        @Query("q") query: String,
        @Query("type") type: String,
        @Query("maxResults") maxResults: Int,
        @Query("key") apiKey: String
    ): VideoResponse
}


3) 데이터 모델 정의
API 응답을 매핑할 데이터 모델을 정의한다. API 응답 JSON 구조에 따라 달라진다.

data class VideoResponse(
    val items: List<VideoItem>
)

data class VideoItem(
    val id: VideoId,
    val snippet: Snippet
)

data class VideoId(
    val videoId: String
)

data class Snippet(
    val title: String,
    val description: String,
    val thumbnails: Thumbnails,
    val publishedAt: String
)

data class Thumbnails(
    val high: Thumbnail
)

data class Thumbnail(
    val url: String
)


4) Retrofit 인스턴스 생성

object RetrofitClient {
    private const val BASE_URL = "https://www.googleapis.com/youtube/v3/"

    private val logger = HttpLoggingInterceptor().apply { 
        level = HttpLoggingInterceptor.Level.BODY 
    }

    private val client = OkHttpClient.Builder()
        .addInterceptor(logger)
        .build()

    val retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val apiService: ApiService = retrofit.create(ApiService::class.java)
}


5) ViewModel에서 데이터 가져오기
ViewModel에서 API 호출을 통해 데이터를 가져오고 LiveData 또는 StateFlow로 관리한다.

class VideoViewModel : ViewModel() {
    private val _videos = MutableStateFlow<List<VideoItem>>(emptyList())
    val videos: StateFlow<List<VideoItem>> get() = _videos

    fun searchVideos(query: String) {
        viewModelScope.launch {
            try {
                val response = RetrofitClient.apiService.searchVideos(
                    part = "snippet",
                    query = query,
                    type = "video",
                    maxResults = 10,
                    apiKey = "YOUR_API_KEY"
                )
                _videos.value = response.items
            } catch (e: Exception) {
                // Handle error
            }
        }
    }
}


6) UI에서 데이터 관찰 및 표시
Fragment 또는 Activity에서 ViewModel의 데이터를 관찰하고 UI에 표시한다.

class VideoFragment : Fragment() {
    private val viewModel: VideoViewModel by viewModels()
    private lateinit var videoAdapter: VideoAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = FragmentVideoBinding.inflate(inflater, container, false)
        videoAdapter = VideoAdapter()

        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = videoAdapter
        }

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        lifecycleScope.launchWhenStarted {
            viewModel.videos.collectLatest { videos ->
                videoAdapter.submitList(videos)
            }
        }

        viewModel.searchVideos("Your search query")
    }
}

728x90

'앱 개발 > Kotlin_Android' 카테고리의 다른 글

MVVM 패턴 사용 이유  (0) 2024.06.11
Android 4대 컴포넌트  (0) 2024.06.07
Hilt & ViewModel  (0) 2024.05.31
검색 버튼 클릭시 키보드 숨김 처리  (0) 2024.05.31
Entity, Mapper  (0) 2024.05.28