Search code examples
kotlinpostrequestretrofithttpresponse

@POST request using Retrofit and Kotlin


when I try to POST with Postman everything work fine:

POST
https://trackapi.nutritionix.com/v2/natural/nutrients

HEADERS

Content-Type : application/json
x-app-id : *******
x-app-key : *******
x-remote-user-id : 0

BODY

{
"query":"carrot"
}

RESULT

{
"foods": [
    {
        "food_name": "carrot",
        "brand_name": null,
        "serving_qty": 1,
        "serving_unit": "carrot",
        "serving_weight_grams": 46,
        "nf_calories": 16.1,
        "nf_total_fat": 0.08, .........

But, when I try this in my app, I have null response. I try with 2 different ways but unfortunately no result.

First:

@Headers(
    "Content-Type: application/json",
    "x-app-id: $NUTRITIONIX_APPLICATION_ID",
    "x-app-key: $NUTRITIONIX_API_KEY",
    "x-remote-user-id: 0",
)
@POST("v2/natural/nutrients")
suspend fun pushFoodNutrients(
    @Body query: String
): Response<FoodNutrientsResponse>

Second:

@FormUrlEncoded
@Headers(
    "Content-Type: application/json",
    "x-app-id: $NUTRITIONIX_APPLICATION_ID",
    "x-app-key: $NUTRITIONIX_API_KEY",
    "x-remote-user-id: 0",
)
@POST("v2/natural/nutrients")
suspend fun pushFoodNutrientsTest(
    @Field("query") query: String
): Response<FoodNutrientsResponse>

Where is my mistake? I searched the internet all day but couldn't find anything.


Solution

  • So, I found the solution.

    This was the good one but with one change.

    @Headers(
    "Content-Type: application/json",
    "x-app-id: $NUTRITIONIX_APPLICATION_ID",
    "x-app-key: $NUTRITIONIX_API_KEY",
    "x-remote-user-id: 0",
    )
    @POST("v2/natural/nutrients")
    suspend fun pushFoodNutrients(
    @Body postModel: PostModel      // what I have changed
    ): Response<FoodNutrientsResponse>
    

    I created an object PostModel with one field query like this:

    data class PostModel(
        val query: String
    )
    

    After that everything works fine.