101

I am new to retrofit 2 library.I read several articles to get started as a beginner and I managed to fetch XML data from my RESTful API without specifying parameters.In my method that generated the XML resource is below.

@GET
@Path("/foods")
@Produces(MediaType.APPLICATION_XML)
public List<FoodPyramid> getFoodPyramid() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    trans = session.beginTransaction();
    List<FoodPyramid> foodList = session.createQuery("from FoodPyramid").list();
    try {
        trans.commit();
        session.close();
    } catch (Exception e) {
        session.close();
        System.err.println("Food Pyramid fetch " + e);
    }
    System.err.println("Am in the food modal. . . . . . . .");
    return foodList;
}

Now when I tried to pass parameter in the interface

@GET("user/{username}/{password}")
Call<List<UserCredentail>> getUserOuth(@Query("username") String username, @Query("password") String password);  

It failed to run,no data was receive by a client . It took me a week trying to fix it though by using a non parameter call fetched the resources; So tried to change it to:

@GET("user/{username}/{password}")
Call<List<UserCredentail>> getUserOuth(@Path("username") String username, @Path("password") String password);  

and it worked fine. So My question is: When do I need to use @Query and @Path Annotation in retrofit 2?

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Mwesigye John Bosco
  • 1,148
  • 2
  • 11
  • 14

8 Answers8

280

Consider this is the url:

www.app.net/api/searchtypes/862189/filters?Type=6&SearchText=School

Now this is the call:

@GET("/api/searchtypes/{Id}/filters")
Call<FilterResponse> getFilterList(
          @Path("Id") long customerId,
          @Query("Type") String responseType,
          @Query("SearchText") String searchText
);

So we have:

www.app.net/api/searchtypes/{Path}/filters?Type={Query}&SearchText={Query}

Things that come after the ? are usually queries.

Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
  • 1
    Helped me alot as well! There is difference between query and path – Hardy Oct 11 '19 at 03:41
  • then what is & mean in this url? and in url type={query} but in @query("type") sting responsetype , so how = sign is inserted in this url? i confused about this issue – Adnan haider Nov 25 '20 at 10:31
28

For example:

@GET("/user/{username}?type={admin}")

Here username is the path variable, and type is the query variable

@GET("/user/{username}?type={admin}")
void getUserOuth(@Path("username") String username, @Query("type") String type)
Nikson Kanti Paul
  • 3,394
  • 1
  • 35
  • 51
  • 3
    Doesn't it require to be **type** instead of **admin** as _@Query_ parameter? As: `void getUserOuth(@Path("username") String username, @Query("type") String type)` – dazed'n'confused Oct 11 '18 at 05:21
8

Kotlin Answer

For example, geting specific post from list with post id:

@GET("Posts/{post_id}")
suspend fun getPost(@Path("post_id") postId: String): Response<Post>

Note: In this example, Post is my data model class.

canerkaseler
  • 6,204
  • 45
  • 38
6

@Query

  • This annotation represents any query key value pair to be sent along with the network request

@Path

  • This annotation implies that the passed parameter will be swapped in the endpoint path
skillsmuggler
  • 1,862
  • 1
  • 11
  • 16
Mina
  • 61
  • 1
  • 5
4

@Path annotation use for ordering parameters as your own way. And defined the order in url.

@GET("user/{username}/{password}")
Call<List<UserCredentail>> getUserOuth(@Path("username") String username, @Path("password") String password);

@Query annotation auto order of parameters and added with url including "?" symbol.

   @GET("user")
    Call<List<UserCredentail>> getUserOuth(@Query("username") String username, @Query("password") String password);
Majedur
  • 3,074
  • 1
  • 30
  • 43
4

Path is use to replace item defined in your path, like

@POST("setting/update_notification_status/{c_notification_id}")
Call<JsonObject> updateNotificationStatus(@Header("Sessionkey") String token, @Path("c_notification_id") String c_notification_id );
3

@Path is used when you have url which has '/' dynamic value after a backword slash.Example "http://google.com/index.html/userid. So in this url /userid is dynamic so to access this url your request should be @Get("index.html/{userid}") Calldata(@Path("userid")int id);

@Query is used when you have a url which has '?' dynamic value after a question mark.Example "http://google.com/index.html?userid.So in this url ? userid is dynamic so to access this url your request should be @Get("index.html") Calldata(@Query("userid")int id);

2

Query is use for URL parameters and with @Query("password") the URL should be :

user/john?password=****

Path is use to replace item defined in your path, like

user/{username}
Johann67
  • 385
  • 6
  • 16