Retrofit: Turn Your HTTP API into an Interface
Retrofit turns your HTTP API into a simple interface, letting you define network calls as annotated methods. It's the standard for most Android network tasks. Footgun: forgetting to run calls off the main thread will crash your app.
WHY IT EXISTS: Manually building HTTP requests is tedious and error-prone. You have to handle URL encoding, request bodies, headers, and response parsing. This boilerplate code clutters your application logic and is hard to maintain. Retrofit was created to automate this entire process.
THE MENTAL MODEL: Think of Retrofit as a translator for your API. You write down the 'phrases' you want to say to your server in a clean interface (the phrasebook), and Retrofit handles the complex 'grammar' of HTTP to make the actual call and understand the response.
HOW IT WORKS: You start by defining a Java or Kotlin interface. On each method, you use annotations to describe the HTTP request. For example, @GET("users/{id}") specifies an HTTP GET request to the users/ endpoint. Method parameters with annotations like @Path("id") or @Query("sort") dynamically fill in parts of the URL. You then create a Retrofit instance with a base URL and a converter factory (like Gson or Moshi) to handle JSON parsing. Finally, you call retrofit.create(YourApiInterface.class) to get a ready-to-use object that implements your interface. Calling a method on this object returns a Call which you can execute synchronously or asynchronously.
WHEN TO USE IT: Use Retrofit for nearly all standard REST API communication in an Android application. It excels at fetching data for display, posting user-generated content, and handling authentication flows. Its integration with converters makes parsing JSON or XML into your data models seamless.
WHEN NOT TO USE IT: For very simple, one-off requests where adding a whole library feels like overkill, a basic HTTP client like OkHttp (which Retrofit uses under the hood) might suffice. For non-HTTP protocols or when you need fine-grained control over raw sockets, Retrofit is not the right tool.
ONE CANONICAL EXAMPLE: To fetch a list of repositories for a GitHub user, you define an interface method: public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }. Then, you create the service and make the call: GitHubService service = retrofit.create(GitHubService.class); Call<List<Repo>> repos = service.listRepos("square"); repos.enqueue(...). This call executes asynchronously, delivering the result or an error in a callback.
Read the original → square.github.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.