How to Model Network API Responses with EitherNet

May 26, 2024 | Programming

In the world of programming, handling API responses efficiently and elegantly is crucial. Enter EitherNet – a multiplatform, pluggable, and sealed API result type designed specifically for modeling network API responses. This guide will walk you through the basics of Using EitherNet with Retrofit, its error handling capabilities, and even how to implement retries for your network requests.

Understanding the Basics

EitherNet provides a streamlined approach to manage API responses from Retrofit without the hassle of traditional error handling methods. Let’s break it down with an analogy:

Imagine you’re sending a letter (your API request) through a postal service (the network). Normally, you might receive either:

  • The letter reaches its destination successfully (Success)
  • There may be various issues that prevent the delivery (Failures):
    • Network issues (NetworkFailure)
    • API errors (ApiFailure)
    • HTTP errors (HttpFailure)
    • Unforeseen issues (UnknownFailure)

EitherNet helps you categorize these results using Kotlin’s sealed classes to avoid the complexities of exceptions.

Installing EitherNet

To get started, you need to include EitherNet in your project. If you’re using Gradle, add the following dependencies:

implementation(com.slack.eithernet:eithernet:version)
implementation(com.slack.eithernet:eithernet-integration-retrofit:version)
testImplementation(testFixtures(com.slack.eithernet:eithernet:version))

Using EitherNet with Retrofit

Now that you have it installed, here’s how to leverage EitherNet for your API responses:

interface TestApi {
    @GET()
    suspend fun getData(): ApiResult
}

When setting up your Retrofit instance, include the call adapter and the converter factory provided by EitherNet:

val api = Retrofit.Builder()
    .addConverterFactory(ApiResultConverterFactory)
    .addCallAdapterFactory(ApiResultCallAdapterFactory)
    .build()
    .create(TestApi::class.java)

Error Handling Made Easy

When you fetch data, you can handle the result using simple, clean when branches:

when (val result = myApi.getData()) {
    is Success -> doSomethingWith(result.response)
    is Failure -> when (result) {
        is NetworkFailure -> showError(result.error)
        is ApiFailure -> showError(result.error)
        is HttpFailure -> showError(result.code)
        is UnknownFailure -> showError(result.error)
    }
}

This approach allows for a structured and concise error handling process.

Decoding Error Bodies

If an HTTP failure occurs with error bodies, you can decode those errors by annotating your endpoint with @DecodeErrorBody. This way, you can handle the error responses more seamlessly:

interface TestApi {
    @DecodeErrorBody
    @GET()
    suspend fun getData(): ApiResult
}

Implementing Retries

To enhance network resilience, EitherNet provides a built-in method for retrying requests with exponential backoff. Here’s a simple example:

val result = retryWithExponentialBackoff(
    maxAttempts = 3,
    initialDelay = 500.milliseconds,
    delayFactor = 2.0,
    maxDelay = 10.seconds
) { api.getData() }

Testing with EitherNet

Testing is made easy with EitherNet’s Test Fixtures, simulating responses for your API requests. You can create a controller instance and enqueue results as needed:

val controller = newEitherNetController()
val provider = PandaDataProvider(controller.api)
controller.enqueue(PandaApi::getPandas, ApiResult.success(Po))

This allows you to precisely manage endpoints and their responses during testing.

Troubleshooting

If you encounter issues while implementing EitherNet, here are some troubleshooting tips:

  • Ensure that all dependencies are correctly added to your build.gradle file.
  • Double-check the annotations on your Retrofit interface to confirm they match the expected types.
  • Validate that your API endpoints are correctly set up in the networking layer.
  • If you’re facing issues specific to the Result types, make sure you are leveraging the sealed classes properly.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Conclusion

EitherNet provides a structured approach to managing API responses, making your coding life simpler. By leveraging Kotlin’s sealed types, your error handling becomes both elegant and efficient. At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox