retrofit get request returns null Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of retrofit get request returns null without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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>)

Answer

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
)
We are here to answer your question about retrofit get request returns null - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji