Member-only story
Android Interview Question Answer : Retrofit Explained
Continue your Android interview preparation with Part 3 of our series! Covering advanced concepts, best practices, and real-world Android development interview questions. Read Part 2 here link on MVVM
Retrofit
What are the advantages of using Retrofit over other networking libraries like Volley?
Retrofit offers several advantages over Volley, including a simpler and type-safe interface for consuming RESTful APIs, streamlined JSON parsing, better support for complex data structures, and greater flexibility for customization, making it easier to manage network requests and handle responses in your Android application.
Explain usage of annotations like
@POST,@GET
,@PUT
,@DELETE
in Retrofit?
@GET
: Used for HTTP GET requests to retrieve data.@POST
: This is used for sending data to the server (e.g., creating a new resource).@PUT
: This is used to update an existing resource.@DELETE
: This is used to delete a resource.
Used for HTTP GET requests to retrieve data from api.
interface APIInterface {
@GET("/api/listUsers")
suspend fun doGetListResources():<MultipleResource>
@POST("/api/saveuser")
suspend fun createUser(@Body user: User): User
@PUT("/api/updateuser?")
suspend fun updateUser(@Query("page") page: String): List<User>
@DELETE("/api/deleteuser?")
suspend fun delteUser(@Query("page") page: String): List<User>
}
What is the difference between @Path and @Query Annotation in retrofit?
@Query
and @Path
are annotations used to define how parameters should be added to the HTTP request
Query is used when you want to add query parameters to a GET request. while Path annotation is used to replace parts of the URL path with values.
Code Example:
//This is an example of @Path annotation
@GET("users/{id}") // it will look like this baseURL+users/1
Call<User> getUser(@Path("id") int userId);
//This is example of Query params
@GET("users")
Call<User> getUser(@Query("id") int userId);// it will look like this baseURL?id=1
Can you explain the steps involved in making a network request using Retrofit?