VizGhar
VizGhar

Reputation: 3128

Retrofit - use query parameter with prefix

I have small problem I'd like to solve. I need to create retrofit Service for following request

https://www.googleapis.com/books/v1/volumes?q=isbn:9788087270431

And my API currently looks like:

public interface GoogleBooksApi {

    @GET("/books/v1/volumes")
    Call<BookResponse> getBooksByIsbn(@Query("q") String isbn);

}

But I have to use prefix "isbn:" every time. Can somebody tell me how to correctly do this?

Upvotes: 0

Views: 735

Answers (1)

jyanks
jyanks

Reputation: 2396

The issue here seems to be that you're misunderstanding the actual parameter that your call to getBooks is expecting.

@GET("/books/v1/volumes")
Call<BookResponse> getBooksByIsbn(@Query("q") String isbn);

Should actually be

@GET("/books/v1/volumes")
Call<BookResponse> getBooks(@Query("q") String query);

And then you can wrap the call to the API in a call like:

public void findByIsbn(String isbn) {
    GoogleBooksApi api = restAdapter.create(GoogleBooksApi.class);
    String query = buildIsbnQuery(isbn);
    api.getBooks(query);
}

public String buildIsbnQuery(String isbn) {
    return String.format("isbn:%s");
}

That way, if the requirement is no longer ISBN's, you don't have to change the actual functionality of your api code, you just need to add an additional query builder method, which makes it respect open-closed principal.

Changing the retrofit code is not advisable and completely not necessary.

Upvotes: 2

Related Questions