Search code examples
androidkotlinretrofit2

Retrofit2 POST String body


I'm making a POST request to the IGDB api which returns a JSON List. If the POST request has an empty body, it will return only the id in incremental order like this. postman request with body

postman request without body

I tried passing the body as a String on my Api Interface like so

interface GameApiClient {


    @Headers(
        "Client-ID: XXXXXXXXXXXXXXXXXXXXXX",
        "Authorization: Bearer XXXXXXXXXXXXXX",
        "Accept: */*"
    )
    @POST("games")
    suspend fun getAllGames(@Body query: String): Response<List<Game>>
}

class GameService {


    private val retrofit = RetrofitHelper.getRetrofit()

    suspend fun getGames(): List<Game> {
        return withContext(Dispatchers.IO) {
            val response = retrofit.create(GameApiClient::class.java)
                .getAllGames("fields id, name; where status = (0, 2, 3, 4); offset  0; where rating>0;")
            response.body() ?: emptyList()
        }
    }
}

But it returns it as if I didnt pass any body to the interface Response inside android studio


Solution

  • I had to add a RequestBody with the MediaType text/plain and it works ok.

        suspend fun getGames(): List<Game> {
            return withContext(Dispatchers.IO) {
    
                val body = RequestBody.create(MediaType.get("text/plain; charset=utf-8"), "fields id, name, summary; where status = (0, 2, 3, 4);")
                val response = retrofit.create(GameApiClient::class.java)
                    .getAllGames(body)
                response.body() ?: emptyList()
            }
        }