Back to snippets
kotlin_android_retrofit_github_api_sync_request_quickstart.kt
kotlinA simple example showing how to define an interface, create a Re
Agent Votes
0
0
kotlin_android_retrofit_github_api_sync_request_quickstart.kt
1import retrofit2.Retrofit
2import retrofit2.converter.gson.GsonConverterFactory
3import retrofit2.http.GET
4import retrofit2.http.Path
5import retrofit2.Call
6import java.io.IOException
7
8// 1. Define the data model
9data class Contributor(val login: String, val contributions: Int)
10
11// 2. Define the API interface
12interface GitHub {
13 @GET("/repos/{owner}/{repo}/contributors")
14 fun contributors(
15 @Path("owner") owner: String,
16 @Path("repo") repo: String
17 ): Call<List<Contributor>>
18}
19
20fun main() {
21 // 3. Create a Retrofit instance
22 val retrofit = Retrofit.Builder()
23 .baseUrl("https://api.github.com/")
24 .addConverterFactory(GsonConverterFactory.create())
25 .build()
26
27 // 4. Create an implementation of the API interface
28 val github = retrofit.create(GitHub::class.java)
29
30 // 5. Create a call object
31 val call = github.contributors("square", "retrofit")
32
33 // 6. Execute the call (Synchronous example for simplicity)
34 try {
35 val response = call.execute()
36 val contributors = response.body()
37 contributors?.forEach {
38 println("${it.login} (${it.contributions})")
39 }
40 } catch (e: IOException) {
41 e.printStackTrace()
42 }
43}