How to Use Retrofit in Android: Simple Guide with Example
To use
Retrofit in Android, add its dependency, create a service interface with HTTP annotations, and build a Retrofit instance to make network calls. Then, call the service methods asynchronously to fetch data from APIs easily.Syntax
Retrofit requires defining a service interface with HTTP method annotations like @GET or @POST. Then, create a Retrofit instance specifying the base URL and converter factory. Finally, use the service to make calls.
interface ApiService: Defines API endpoints.@GET("path"): HTTP GET request annotation.Retrofit.Builder(): Builds Retrofit instance.create(ApiService.class): Creates service implementation.
java
public interface ApiService { @GET("users") Call<List<User>> getUsers(); } Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService service = retrofit.create(ApiService.class);
Example
This example shows how to fetch a list of users from an API using Retrofit asynchronously and display the result in logs.
java
public interface ApiService { @GET("users") Call<List<User>> getUsers(); } Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://jsonplaceholder.typicode.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService service = retrofit.create(ApiService.class); service.getUsers().enqueue(new Callback<List<User>>() { @Override public void onResponse(Call<List<User>> call, Response<List<User>> response) { if (response.isSuccessful() && response.body() != null) { for (User user : response.body()) { Log.d("RetrofitExample", "User: " + user.getName()); } } } @Override public void onFailure(Call<List<User>> call, Throwable t) { Log.e("RetrofitExample", "Error: " + t.getMessage()); } }); // User class with getName() method assumed
Output
Logs showing user names fetched from the API or error messages if failed.
Common Pitfalls
Common mistakes include forgetting to add the GsonConverterFactory, calling network methods on the main thread, or not handling null responses properly.
Also, ensure internet permission is declared in AndroidManifest.xml.
java
/* Wrong: Missing converter factory causes parsing errors */ Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .build(); /* Right: Add Gson converter for JSON parsing */ Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build();
Quick Reference
- Add Retrofit and Gson dependencies in
build.gradle. - Define API interface with HTTP annotations.
- Create Retrofit instance with base URL and converter.
- Use
enqueue()for async calls. - Handle responses and failures properly.
Key Takeaways
Add Retrofit and Gson dependencies before using Retrofit in Android.
Define API endpoints in an interface with HTTP method annotations.
Build a Retrofit instance with base URL and converter factory.
Use asynchronous calls with enqueue() to avoid blocking the main thread.
Always handle API responses and errors to prevent crashes.