Home > Back-end >  Dynamic Url with @Post request retrofit hilt
Dynamic Url with @Post request retrofit hilt

Time:06-21

I am trying with Hilt and Retrofit2 to create a Post request with a dynamic URL.

I am getting the error @Url cannot be used with @POST URL (parameter #1)

I need the query to be dynamic too

@POST("{id}")
suspend fun getConfiguration(
    @Url url: String,
    @Body configRequest: ConfigRequest,
    @Query("id") id: String
): Config

the builder

@ExperimentalSerializationApi
@Provides
@Singleton
fun provideApi(@ApplicationContext context: Context): Api{
    val contentType = "application/json".toMediaType()
    val json = Json {
        explicitNulls = false
        coerceInputValues = true
        ignoreUnknownKeys = true
    }
    return Retrofit.Builder()
        .baseUrl(Constants.BASE_URL)
        .client(RetrofitHelper.getOkHttpClient(context))
        .addConverterFactory(json.asConverterFactory(contentType))
        .build()
        .create(Api::class.java)
}

Any work arounds?

CodePudding user response:

@Url is a parameter annotation allows passing a complete URL for an endpoint, so it's not a base url, but it's the full endpoint url, and you can't use it with dynamic path @POST("{id}"), this must be like that @POST() and also @Querycan't be used with @Url, so you have two solutions:

  1. The first is by keeping @Url and generate the full url by yourself (generate a url will the query) and give it to getConfiguration(url) function:

code:

@POST()
suspend fun getConfiguration(
    @Url url: String,
): Config
  1. The second which is not recommended but it's easier, which is creating a new retrofit instance with the other base url and other api interface provided by the new retrofit instance, and with you can keep using Query:

code:

@POST("{id}")
suspend fun getConfiguration(
    @Body configRequest: ConfigRequest,
    @Query("id") id: String
): Config
  • Related