Warm tip: This article is reproduced from stackoverflow.com, please click
android kotlin retrofit

How would I parameterise this endpoint using Retrofit please?

发布于 2020-03-31 22:54:16

Say I want to query an an API which has a server method for searching for a field containing certain text like so:

http://server:2001/tms/xdata/Customer?$filter=contains(Name, 'Walker') 

In Android Studio using Kotlin I would make an interface something like this:

    @GET("/tms/xdata/Customer")
    suspend fun fetchAllProductsContaining(@Query("name") searchTerm: String): CustomersResponse

which if I pass a single character 'e' as the searchTerm would give me:

http://server:2001/tms/xdata/Customer?name=e

However I need it to look like this:

http://server:2001/tms/xdata/Customer?%24filter=contains(lower(name)%2C'e')

As I want it to be case insensitive, also notice the text to search for has to have single quotes around it.

I would very much appreciate any help you guys might have. The server is written in Delphi using TMS XData

Questioner
Steve
Viewed
15
Steve 2020-02-03 19:11

The answer is to use QueryMap. Call the function this way:

    suspend fun searchProductsRetrofit(searchTerm: String): List<Product> {
        val options: MutableMap<String, String> = HashMap()
        options["\$filter"] = "contains(lower(Name),'$searchTerm')"
        return retrofit().getProducts(options).value
    }

In your API interface configure it to use the passed in data as follows:

    @GET("/pmi/civic_amenity/CaProduct")
    suspend fun getProducts(@QueryMap options: Map<String, String>): ProductsResponse