Home > Mobile >  retrofit get request returns null
retrofit get request returns null

Time:11-29

I use extract articles from news api and display them using paging 3 library in my project, but for some reason @GET request returns my response class but with null variable though on my profile on the news api site it shows that there was a request.

NewsApi class:

interface NewsApi {

companion object{
    const val CLIENT_ID = "356d64b4bfde4cd492ef415beabba030"
    const val BASE_URL = "https://newsapi.org/"
}

@Headers("X-Api-Key: ${CLIENT_ID}")
@GET("v2/everything")
suspend fun searchArticles (
    @Query("q") query: String,
    @Query("page") page: Int,
    @Query("pageSize") pageSize: Int,
) : NewsResponse

}

My Response class:

data class NewsResponse (
val results: List<NewsArticle>)

CodePudding user response:

I tried your api and fetch the result, Your Api is fine, the problem is you try to get the result as

data class NewsResponse (
val results: List<NewsArticle>)

when the result is actually formed like this :

{
"status":"ok",
"totalResults":14925,
"articles":[
{
"author":"Igor Bonifacic",
"title":"University of ",
"description":"In aide built a robot to com…"
}
]
}

so change you result into :

data class NewsResponse(
    val status : String,
    val totalResults: Int,
    val articles: List<NewsArticle>
)

data class NewsArticle(
    val author: String,
    val description: String
)
  • Related