Junior
What needs to be done to describe a GET request?
sobes.tech AI
Answer from AI
REST interface, URL, HTTP GET method.
interface ApiService {
@GET("/api/v1/items") // Description of GET request with path
suspend fun getItems(): List<Item> // Function to execute request, returning a list of Item
}
Using the Retrofit2 library to create a client and execute requests.
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/") // Base URL of the API
.addConverterFactory(GsonConverterFactory.create()) // Converter for parsing JSON
.build()
val apiService = retrofit.create(ApiService::class.java) // Creating an instance of the service
// Executing the request in a coroutine or another thread
try {
val items = apiService.getItems()
// Processing the received data
} catch (e: Exception) {
// Error handling
}
Depending on the task, request parameters (Query Parameters) or headers (Headers) may be required.
interface ApiService {
@GET("/api/v1/items")
suspend fun getItems(
@Query("category") category: String? = null, // Query parameter "category"
@Header("Authorization") authHeader: String // Header "Authorization"
): List<Item>
}