Android Networking with Retrofit
Instructions
When implementing network layers using Retrofit, follow these modern Android best practices (2025).
1. URL Manipulation
Retrofit allows dynamic URL updates through replacement blocks and query parameters.
- Dynamic Paths: Use
{name}in the relative URL and@Path("name")in parameters. - Query Parameters: Use
@Query("key")for individual parameters. - Complex Queries: Use
@QueryMap Map<String, String>for dynamic sets of parameters.
2. Request Body & Form Data
You can send objects as JSON bodies or use form-encoded/multipart formats.
- @Body: Serializes an object using the configured converter (JSON).
- @FormUrlEncoded: Sends data as
application/x-www-form-urlencoded. Use@Field. - @Multipart: Sends data as
multipart/form-data. Use@Part.
3. Header Manipulation
Headers can be set statically for a method or dynamically via parameters.
- Static Headers: Use
@Headers. - Dynamic Headers: Use
@Header. - Header Maps: Use
@HeaderMap. - Global Headers: Use an OkHttp Interceptor.
4. Kotlin Support & Response Handling
When using suspend functions, you have two choices for return types:
- Direct Body (
User): Returns the deserialized body. ThrowsHttpExceptionfor non-2xx responses. Response<User>: Provides access to the status code, headers, and error body. Does NOT throw on non-2xx results.
5. Hilt & Serialization Configuration
Provide your Retrofit instances as singletons in a Hilt module.
6. Error Handling in Repositories
Always handle network exceptions in the Repository layer to keep the UI state clean.
7. Checklist
- Use
suspendfunctions for all network calls. - Prefer
Response<T>if you need to handle specific status codes (e.g., 401 Unauthorized). - Use
@Pathand@Queryinstead of manual string concatenation for URLs. - Configure
OkHttpClientwith logging (for debug) and sensible timeouts. - Map API DTOs to Domain models to decouple layers.


