Search code examples
androidkotlinretrofitretrofit2

How to have dynamic API endpoints in retrofit based on ids?


I want to be able to use a dynamic API endpoint URL to get specific data. I was already able to use a fixed URL in my @GET("endpoint"), which works,, but I don't know how to use it dynamically.

I set up my class as follows:

class WebService {
    private lateinit var api: MyApi

    init {
        val retrofit = Retrofit.Builder()
            .baseUrl("https://myUrl.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        api = retrofit.create(MyApi::class.java)
    }
    suspend fun getData(): MyResponse {
        return api.getData()
    }

    interface MyApi {
        @GET("/my/endpoint/1")
        suspend fun getData(): MyResponse
    }
}

How would I be able to reformat it so that I can make it @GET("/my/endpoint/MY_ID")?


Solution

  •     interface MyApi {
        @GET("/my/endpoint/{myId}")
        suspend fun getData(@Path("myId") myId:String): MyResponse
    }