Network requests.

Most apps fetch data from the internet. User profiles from a server. Products from an API. News from a feed. Today we learn how to make network requests in Android using Retrofit and coroutines.

Apps communicate with servers over HTTP.

HTTP requests have a method. GET retrieves data. POST sends data. PUT updates. DELETE removes.

Requests go to a URL. https api example com users. The server processes and returns a response.

Responses have a status code. 200 is success. 404 is not found. 500 is server error.

Response body contains data. Often JSON format. We parse it into objects.

Retrofit is the standard library for HTTP in Android.

You define an interface describing the API. Retrofit generates the implementation.

No manual HTTP connection code. No parsing JSON manually. Retrofit handles it.

Retrofit works with coroutines. Suspend functions for requests. Non-blocking calls.

Retrofit works with various serialization libraries. We use kotlinx dot serialization.

Describe your API as an interface.

interface UserApi at GET "users" suspend fun getUsers colon List of UserDto at GET "users slash userId" suspend fun getUser at Path "userId" id colon Int colon UserDto.

at GET, at POST, at PUT, at DELETE mark the HTTP method.

The string is the path. Combined with base URL.

at Path inserts a value into the path. at Query adds query parameters.

Return type is parsed from JSON. Suspend makes it non-blocking.

Create a Retrofit instance.

Retrofit dot Builder dot baseUrl "https api example com" dot addConverterFactory... dot build.

Base URL is the server address. All paths are relative to it.

Converter factory handles serialization. We use kotlinx dot serialization converter.

Create the API implementation. retrofit dot create UserApi class java.

One Retrofit instance per base URL. Reuse it.

API methods are suspend functions.

val users equals userApi dot getUsers. This suspends until the response arrives.

Call from a coroutine. viewModelScope dot launch brace val users equals api dot getUsers close brace.

Network I/O happens automatically on background thread. Retrofit handles it.

No callback hell. No RxJava complexity. Just sequential code that suspends.

Errors throw exceptions. Wrap in try-catch or use Result type.

Retrofit can return Response wrapper.

suspend fun getUser id Int colon Response of UserDto.

Check if successful. if response dot isSuccessful brace response dot body close brace.

Access status code. response dot code. Access error body. response dot errorBody.

For simple cases, return the type directly. Retrofit throws on non-2xx.

For complex error handling, return Response and check manually.

Network calls can fail in many ways.

Network unavailable. Server unreachable. Timeout. Server returns error.

Wrap calls in try-catch. Catch IOException for network errors. Catch HttpException for HTTP errors.

try brace api dot getUsers close brace catch e IOException brace network error close brace catch e HttpException brace server error close brace.

Show appropriate messages to users. Retry options. Offline fallback.

kotlinx dot serialization parses JSON.

Mark data classes with at Serializable. at Serializable data class UserDto val id colon Int, val name colon String.

Property names map to JSON keys. Customize with at SerialName.

at SerialName "user_name" val name colon String. JSON key is user_name.

Default values handle optional fields. val age colon Int equals 0. Missing in JSON, uses default.

Add the converter to Retrofit. addConverterFactory kotlinx serialization converter.

Let us summarize.

HTTP is the protocol. GET, POST, PUT, DELETE are common methods.

Retrofit generates API implementations from interfaces.

Suspend functions make network calls non-blocking.

Handle responses and errors appropriately.

kotlinx dot serialization parses JSON with annotated data classes.

Network requests are foundational for connected apps.