<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrea Prearo on Medium]]></title>
        <description><![CDATA[Stories by Andrea Prearo on Medium]]></description>
        <link>https://medium.com/@andreaprearo?source=rss-74b5380ff1ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8Q75F48ggjRBQG2_ycNWcg.jpeg</url>
            <title>Stories by Andrea Prearo on Medium</title>
            <link>https://medium.com/@andreaprearo?source=rss-74b5380ff1ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:02:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreaprearo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kotlin Multiplatform Mobile (KMM) at Granular]]></title>
            <link>https://medium.com/granular-engineering/kotlin-multiplatform-mobile-kmm-at-granular-983f7becfd52?source=rss-74b5380ff1ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/983f7becfd52</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Andrea Prearo]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 18:16:46 GMT</pubDate>
            <atom:updated>2022-03-28T18:16:46.874Z</atom:updated>
            <content:encoded><![CDATA[<p>All mobile developers, sooner or later, are confronted with the following question: “Can we write code that works across iOS and Android?”. Over the years, many tools have been created to be able to achieve the Holy Grail of “Write once, run anywhere”.</p><p>Over the last 2–3 years, the mobile teams at Granular have adopted <a href="https://kotlinlang.org/lp/mobile/">Kotlin Multiplatform Mobile</a> (KMM) to write cross-platform code that works across iOS and Android.</p><h3>What we share across mobile platforms</h3><p>KMM allows mobile teams to keep their UI fully native and share the common business logic (written in Kotlin). But how much of your business code should be shared depends on many factors. Many of the available KMM samples and real world examples tend to draw the upper boundary of the shared code at the data layer or model domain level (through some version of the <a href="https://developer.android.com/jetpack/guide#data-layer">Repository pattern</a>).</p><blockquote><em>API wrapping/integration is one of the most common kind of logic that can be easily shared across mobile platforms using </em><a href="https://ktor.io/"><em>Ktor</em></a><em>. Another one is on-device data persistence which can be easily be taken care of using </em><a href="https://github.com/cashapp/sqldelight"><em>SQLDelight</em></a><em>.</em></blockquote><p>Generally speaking, this allows to adopt different architecture patterns as you get close to the specific platform UI. For instance, your iOS developers may want to use VIPER or MVVM for the iOS app while your Android developers may prefer MVP or MVI.</p><p>At Granular, we decided to be more prescriptive in terms of the desired architectural approach. Our mobile teams agreed to adopt an MVI approach for both platforms (iOS and Android), to maximize our business logic code sharing. Broadly speaking, this means that we’re creating MVI based cross-platform view models on top of what is the common type of shared business logic (API integration, data layer, persisted settings, …). This allows us to define our specific best practices and patterns to ensure clean separation between platform-specific UI presentation and business logic. This also brings up the interesting topic of observing for data changes from a view model, which likely deserves its own post (stay tuned!).</p><h3>Reusing code across multiple apps</h3><p>At Granular, we have two production apps: Insights and Business. When we started adopting KMM to share our business logic, we wanted to make sure we can easily integrate new functionality into both apps. This was critical for functionality such as SSO which would be extremely wasteful to implement multiple times (once per app and/or once per platform). In addition to that, we also want to make sure we can create platform-specific UI, on top of the KMM shared business logic, that could be reused in multiple apps. The aforementioned SSO functionality is a prime example of this requirement: Wouldn’t be great to build a platform-specific UI login screen and be able to reuse it in every single app that needs to leverage the same SSO functionality?</p><h4>From reusable components to an SDK</h4><p>That’s what we set up to build and, after the initial success with the SSO functionality, we became very fond of building reusable <strong>components</strong> that bundle the necessary KMM shared business logic (up to the view model) with the related platform-specific UI. Nowadays, we approach every new feature with a componentized mindset to make sure from the inception phase that we can easily reuse both the shared logic and the platform-specific UI.</p><blockquote><em>In Granular lingo a </em><strong><em>component</em></strong><em> is usually a software module that is defined by some KMM shared logic and any related platform-specific UI (See </em><em>Fig.2). From the point of view of </em><em>Build and Release engineering, this usually translates in publishing a platform-specific binary artifact (iOS .framework, Android .aar) for each component.</em></blockquote><h4>KMM based Mobile SDK at Granular</h4><p>Our flagship app, Granular Insights, is currently bundling about a dozen feature-oriented reusable components. We also have a few “foundational” libraries containing helper classes and methods commonly used across the codebase, to maximize code reuse. This collection of components and libraries can be bundled together, as needed, to serve as an SDK to allow new internal, or external, teams to start building new mobile apps for their particular agricultural-based use case without having to start from scratch or “reinvent the wheel” (See Fig.1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVgN939GsSRCw22G7kMQ1g.png" /></figure><h3>Learning, challenges, and the way forward</h3><p>Until a couple of years ago, my main focus as a mobile developer has been iOS development. So, naturally, my opinions on KMM are heavily influenced by how easy, or difficult, is to integrate KMM into the usual iOS development workflow.</p><p>Let’s start with some of the more general challenges that apply to both iOS and Android. KMM is still in its early phases, so there aren’t many consolidated standardized best practices in regards to the Kotlin shared code and it’s usually up to the mobile team(s) to decide what works best for them.</p><p>For instance, as you approach KMM, your company mobile team(s) should define how to:</p><ul><li>Inject platform-specific functionality into the shared business logic (for instance, network monitoring).</li><li>Expose your data layer / repository / view model to each platform.</li><li>Structure your teams to be able to work across KMM, iOS and Android in a shared codebase.</li></ul><p>There’s no “one size fits all” here and every company/team needs to figure out what’s the most reasonable approach toward sharing business logic and working together in a shared codebase.</p><p>In regards to KMM-related coding best practices, one iOS specific item we spent quite some time to fully flesh out is how to expose Kotlin Flow to iOS and consume it in Swift. Since we decided to share view models across platform, we opted to go all in with a functional/reactive approach and consume Kotlin Flow through RxSwift. The approach we landed on has been successfully used for some time and we’ll likely implement something similar as we start leveraging SwiftUI and Combine. Similarly to the topic of observing for data changes from a view model, briefly discussed earlier, consuming Kotlin Flow through RxSwift (or Combine) likely deserves its own post so I won’t go into details here.</p><p>I’ll now illustrate some of the specific challenges related to the KMM adoption use case for Granular (i.e.: Building a mobile SDK). Most of the open source KMM examples are covering the use case of embedding the shared Kotlin code into a single app per platform (the same app for Android and iOS). In our use case, since we set out to create an SDK based on reusable components, we need to:</p><ol><li>Support multiple apps on both iOS and Android.</li><li>Leverage the shared Kotlin code to implement platform-specific reusable UI components (iOS and Android) on top of it (as illustrated in Fig.2).</li></ol><p>The real challenge is to achieve the second goal. Once that’s taken care of, building an SDK and supporting multiple apps is rather straightforward using the consolidated platform-specific approaches for dependency management.</p><h4>Reusable UI components challenges and possible approaches</h4><p><strong>KMM and Android work seamlessly</strong></p><p>Creating reusable UI components, dependent on the shared Kotlin code, is relatively seamless on Android. In this scenario all dependencies (shared Kotlin code and Android UI library) can be handled through Gradle without too much effort. Once you become familiar with it, Gradle can fulfill all your needs in terms of build process and dependency management.</p><p><strong>KMM and iOS use different build tools and dependency managers</strong></p><p>For iOS, instead, the situation is more challenging. KMM provides the necessary Gradle tasks for creating iOS binary artifacts (<a href="https://kotlinlang.org/docs/multiplatform-build-native-binaries.html#build-universal-frameworks">universal frameworks</a> and <a href="https://kotlinlang.org/docs/multiplatform-build-native-binaries.html#build-xcframeworks">xcframeworks</a>) from the shared Kotlin code. But we need to be able to invoke the appropriate Gradle task and assemble the shared Kotlin code into the required iOS binary artifact before we can use it as a dependency for a reusable iOS library. This means that, in order to have a seamless iOS development experience, we need to find a way to inject a pre-build phase into the iOS build process, to make sure we assemble the required iOS artifact from the Kotlin code before building the reusable iOS library that depends on it. This requirement translates into being able to inject a pre-build phase (for the shared Kotlin code iOS artifact) through the iOS dependency manager of choice.</p><p>At Granular, we want to be able to support our iOS SDK dependencies through both CocoaPods and SwiftPM. This will allow iOS app implementers to choose the dependency manager they feel most comfortable with. At the time being, we have a solution to inject a pre-build phase (to invoke Gradle) in place for CocoaPods. We’re still exploring this topic in regards to SwiftPM.</p><p>If injecting a pre-build phase in the build process is not feasible, there are some possible workarounds. For instance, every time we make changes to the shared Kotlin code, we could manually invoke the appropriate Gradle task to assemble the iOS binary artifact, before building the dependent iOS UI library. This ensures we get the updated shared code functionality, but also means that additional manual steps are required when updating the iOS UI library. This is mainly a developer workflow challenge. It’s usually easily solvable when running tests through a CICD pipeline, as all the required steps can be easily handled through scripting. But, as you develop using Xcode, you’d likely want to just being able to hit the Run button and have all the required build steps automatically taken care for you. Having to manually invoke the Gradle task, to assemble the iOS binary artifact from the shared Kotlin code as we make changes, before building any dependent iOS library is both extremely tedious and error prone (because it&#39;s really easy to forget to manually invoke the Gradle task).</p><h4>Shared business logic debugging challenges and possible approaches</h4><p><strong>KMM and Android Studio work seamlessly</strong></p><p>As it happens in most scenarios, when working across Android and KMM you find out that the development experience is pretty seamless. Debugging the shared business logic from an Android app running through Android Studio is not really different from what Android developers are used to.</p><p><strong>Xcode doesn’t know about Kotlin</strong></p><p>Of course, Xcode has never been built to support Kotlin. But it’d be really great to be able to debug the shared Kotlin code while running an iOS app through Xcode.</p><p>Kudos to <a href="https://touchlab.co/">Touchlab</a> for providing an <a href="https://github.com/touchlab/xcode-kotlin">xcode-kotlin plugin</a>, which we’ve been experimenting with for some time. The plugin allows to set breakpoints in the shared Kotlin code from Xcode. Variable inspection through LLDB is also supported by the plugin. But the debugger tends to be a bit unstable, especially if you are trying to inspect Kotlin code that is executed inside a coroutine scope. For our teams, this is the most common case as our cross-platform view models are exposing their data through one or more Kotlin flows. In the context of our iOS SDK, the iOS binary artifact for the shared Kotlin code is imported and consumed through a few different Swift frameworks, which can definitely create a more complicated and unstable scenario for the plugin. For simpler scenarios, for instance when leveraging a shared Kotlin repository, the debugger is definitely more reliable.</p><p>At least some of the issues we ran into, when trying to debug Kotlin code from Xcode, are definitely of our own making. Because of the highly functional/reactive nature of our common shared business logic, where much of the high level functionality hinges on a cross-platform view model, debugging would likely be tricky even if all our code was in Swift.</p><p>The combined effect of the above, led us to rely on using print statements as our main approach to debugging Kotlin code from Xcode. How much of an issue this is I think depends mostly on personal preferences/habits as a developer. I’m sure some of the reactive programming purists among us would say we shouldn’t set breakpoints inside reactive code anyway, as it interferes with the threading behavior and may end up altering it altogether, possibly creating concurrency issues that could very well be a by-product of the debugger and not due to the code itself.</p><p><strong>KMM plugin and iOS app</strong></p><p>We also looked into the <a href="https://plugins.jetbrains.com/plugin/14936-kotlin-multiplatform-mobile">KMM Android Studio plugin</a>. Unfortunately, the plugin is not able to build our iOS app, which depends on many Swift frameworks and is also not bundling the shared Kotlin code directly into the app itself (but using it as a dependency for more than a few internal Swift frameworks).</p><h3>Conclusion</h3><p>As mentioned earlier, KMM is still in its early phases. Nevertheless, we think it’s a very promising cross-platform technology: It allows to write fully platform specific UI code (ideally using SwiftUI and Jetpack Compose) and share all the common business logic across mobile platforms.</p><p>We’ve been successfully using KMM in production for about 2–3 years now. As with any technology, after our teams figured out how to deal with some of the rough edges (especially on iOS), we definitely enjoyed the benefits of sharing business logic across mobile platforms. Our plan for the future is to keep writing cross-platform reusable components and keep improving our shared codebase as KMM provides new and improved functionality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983f7becfd52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/granular-engineering/kotlin-multiplatform-mobile-kmm-at-granular-983f7becfd52">Kotlin Multiplatform Mobile (KMM) at Granular</a> was originally published in <a href="https://medium.com/granular-engineering">Granular Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking HTTP calls with Ktor MockEngine]]></title>
            <link>https://medium.com/granular-engineering/mocking-http-calls-with-ktor-mockengine-3269fd807880?source=rss-74b5380ff1ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/3269fd807880</guid>
            <dc:creator><![CDATA[Andrea Prearo]]></dc:creator>
            <pubDate>Wed, 19 Aug 2020 14:54:05 GMT</pubDate>
            <atom:updated>2020-08-19T14:54:05.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcBRA7-9KpOtHQL1cyD0-A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jasonhk1920?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jason Wong</a> on <a href="https://unsplash.com/s/photos/coffee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this post I’m going to illustrate how we can leverage Ktor’s <a href="https://api.ktor.io/1.3.1/io.ktor.client.engine.mock/-mock-engine/index.html">MockEngine</a> to create unit tests for HTTP calls. In order to do that, I’m going to build up on the JSONPlaceholder wrapper code from my <a href="https://medium.com/granular-engineering/multi-platform-mobile-networking-libraries-with-ktor-778315abfe4d">previous post</a>.</p><h3>Mocking JSONPlaceholder API</h3><p>As stated in Ktor’s online documentation, MockEngine provides an <a href="https://api.ktor.io/1.3.1/io.ktor.client.engine/-http-client-engine/index.html">HttpClientEngine</a> for writing tests without network. Basically, it allows us to intercept HTTP calls and return mock responses. This is very useful as it makes writing unit tests for HTTP calls really easy!</p><h4>Creating mock responses</h4><p>The <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> API provides the following resources:</p><ul><li><a href="https://jsonplaceholder.typicode.com/posts"><em>/posts</em></a></li><li><a href="https://jsonplaceholder.typicode.com/comments"><em>/comments</em></a></li><li><a href="https://jsonplaceholder.typicode.com/albums"><em>/albums</em></a></li><li><a href="https://jsonplaceholder.typicode.com/photos"><em>/photos</em></a></li><li><a href="https://jsonplaceholder.typicode.com/todos"><em>/todos</em></a></li><li><a href="https://jsonplaceholder.typicode.com/users"><em>/users</em></a></li></ul><p>Therefore, in order to create unit tests for our HTTP calls, we are going to need a mock response for each resource. To simplify the code I’m going to create the mock responses as static objects with the following general structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/755ffc771d90e9070e3fa1b61236d1cd/href">https://medium.com/media/755ffc771d90e9070e3fa1b61236d1cd/href</a></iframe><p>{Model} will be the name of the top level model class that represents the JSON object returned by a specific resource. This means we are going to need the following objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af29b4828ac2e4af8136ec8f76f70d01/href">https://medium.com/media/af29b4828ac2e4af8136ec8f76f70d01/href</a></iframe><p>In order to limit the size of our mock response objects we can set a predefined number of JSON objects that will be returned. For the sake of this post I decided to return only ten objects for each mock response.</p><h4>JSONPlaceholder API mock engine</h4><p>Now that we have our mock responses in place it’s time to create a MockEngine for JSONPlaceholder. Following the example provided on <a href="https://ktor.io/clients/http-client/testing.html">Ktor’s online documentation</a> we can implement our mock engine for JSONPlaceholder as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d103b3bd88d2c71f7386da4ee1fafab1/href">https://medium.com/media/d103b3bd88d2c71f7386da4ee1fafab1/href</a></iframe><p>The get() method is just a helper to easily access the engine property of an ApiMockEngine instance.</p><p>responseHeaders defines a standard Content-Type: application/json header to be returned by the mock engine.</p><p>The meaty portion is what happens inside the addHandler lambda. The general structure is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c30eb5067aa9634f9dcfa60da38e871/href">https://medium.com/media/4c30eb5067aa9634f9dcfa60da38e871/href</a></iframe><p>Basically, when ApiMockEngine is used to make HTTP calls it will return the specific {Model}MockResponse object (as a JSON string) when the URL path corresponds to the associated {resource}. An HTTP OK (200) code and a standard Content-Type: application/json header will also be part of the response payload.</p><h3>Unit tests for HTTP calls</h3><p>At this point we have everything we need to mock our HTTP calls. Now we just need to be able to leverage the mock engine to write unit tests for our HTTP calls.</p><p><strong>Dependency injection</strong></p><p>In the <a href="https://medium.com/granular-engineering/multi-platform-mobile-networking-libraries-with-ktor-778315abfe4d">previous post</a> we created a class that encapsulates the JSONPlaceholder API functionality. Such a class is instantiating a private instance of <a href="https://api.ktor.io/1.3.1/io.ktor.client/-http-client/index.html">HttpClient,</a> which implements a HttpClientEngine interface, to make HTTP calls:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d3b91f41d63a14f5ece9145a0a227b/href">https://medium.com/media/80d3b91f41d63a14f5ece9145a0a227b/href</a></iframe><p>We can leverage dependency injection to be able to use different implementations of HttpClientEngine for specific purposes. In particular we can pass:</p><ul><li>An HttpClient().engine value for our production code to make (real) HTTP calls over the network.</li><li>An ApiMockEngine instance for mocking HTTP calls in our unit tests.</li></ul><p>We can therefore modify the Api class as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5838c18a9f808a81784b9b9d45a76d2c/href">https://medium.com/media/5838c18a9f808a81784b9b9d45a76d2c/href</a></iframe><p>We can now instantiate Api with the desired engine:</p><ul><li>Api(HttpClient().engine) for production code.</li><li>Api(ApiMockEngine().get()) for unit tests.</li></ul><h4>Unit tests in action</h4><p>The full code for the HTTP calls unit tests is listed below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aa462d2d03807ecbd55b0b47f675179/href">https://medium.com/media/1aa462d2d03807ecbd55b0b47f675179/href</a></iframe><p>In the above unit tests we are calling the specific method for each wrapped JSONPlaceholder resource. Since we injected the ApiMockEngine in the tests we are getting back the corresponding mock response we created earlier. This allows to write assertions to make sure the wrapping method is correctly retrieving and parsing the returned mock response.</p><p>For sake of brevity, in the above tests I’m only checking that the number of parsed objects corresponds to the number of objects defined in each mock response. More assertions can be added as needed to thoroughly check that the parsed objects correspond to the objects provided in the mock response.</p><h3>Conclusion</h3><p>You can find the full code for wrapping JSONPlaceholder <a href="https://github.com/andrea-prearo/JSONPlaceholderKotlin">here</a>.</p><p>In this post we examined how it’s possible to leverage Ktor’s MockEngine to create unit tests for HTTP calls. In particular we saw how we can create our custom mock engine to mock HTTP calls and use HttpClientEngine to be able to inject it for unit testing.</p><p>In the next post we’re going to take a look at how we can create an augmented Ktor exception and create unit tests for it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3269fd807880" width="1" height="1" alt=""><hr><p><a href="https://medium.com/granular-engineering/mocking-http-calls-with-ktor-mockengine-3269fd807880">Mocking HTTP calls with Ktor MockEngine</a> was originally published in <a href="https://medium.com/granular-engineering">Granular Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-platform mobile networking libraries with Ktor]]></title>
            <link>https://medium.com/granular-engineering/multi-platform-mobile-networking-libraries-with-ktor-778315abfe4d?source=rss-74b5380ff1ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/778315abfe4d</guid>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Andrea Prearo]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 17:07:35 GMT</pubDate>
            <atom:updated>2020-07-13T17:07:35.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1ENiiMG1ERabwPNKJazZw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mensroom?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText">Mike Marquez</a> on <a href="https://unsplash.com/s/photos/coffee?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this post I’m going to illustrate how it’s possible to leverage <a href="https://ktor.io/">Ktor</a> to create a shared mobile library that wraps a REST API. The code I’m going to present here can be hosted inside a Kotlin Multi Platform (a.k.a. KMP) project and consumed by any Android and iOS app. For the sake of this post I’m going to target a simple and publicly available API: <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a>.</p><h3>JSONPlaceholder API Overview</h3><p>The JSONPlaceholder API is rather simple and provides online fake data. Here are the available resources:</p><ul><li><a href="https://jsonplaceholder.typicode.com/posts"><em>/posts</em></a></li><li><a href="https://jsonplaceholder.typicode.com/comments"><em>/comments</em></a></li><li><a href="https://jsonplaceholder.typicode.com/albums"><em>/albums</em></a></li><li><a href="https://jsonplaceholder.typicode.com/photos"><em>/photos</em></a></li><li><a href="https://jsonplaceholder.typicode.com/todos"><em>/todos</em></a></li><li><a href="https://jsonplaceholder.typicode.com/users"><em>/users</em></a></li></ul><p>Each one of the above resources returns a predefined number of JSON objects containing fake data representing an entity corresponding to the resource name (i.e.: posts, comments, …).</p><h3>Wrapping the /users resource</h3><p>To limit the scope of this post I’m going to show how it’s possible to create a wrapper for the /users resource. Such a resource returns the most complex data, which uses nested JSON objects, among the resources provided by JSONPlaceholder. All remaining resources can be wrapped the same way and with less effort since they don’t return nested objects.</p><h4>Creating the User model</h4><p>The /users resource returns an array of JSON objects representing fake users. Each user object has the structure shown in the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78f488acf3618a5d24364f94ee2bc002/href">https://medium.com/media/78f488acf3618a5d24364f94ee2bc002/href</a></iframe><p>We can take advantage of Kotlin’s <a href="https://github.com/Kotlin/kotlinx.serialization">@Serializable</a> annotation to create classes to model each user object returned in the JSON. In order to achieve that we are going to need a top level User class and a few nested classes (Address, Company and Geolocation):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70c8502a549d06f57bce8fa4d0a92ae7/href">https://medium.com/media/70c8502a549d06f57bce8fa4d0a92ae7/href</a></iframe><h4>Retrieving and parsing JSON data</h4><p>Now that we have our serializable models in place we will create a class that encapsulates the JSONPlaceholder API functionality. The full code is listed below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f727edeb3e6321d33d3036d239ce74f7/href">https://medium.com/media/f727edeb3e6321d33d3036d239ce74f7/href</a></iframe><p>The /users resource is modeled using an enum class to encapsulate its details.</p><p>Our workhorse is the Api class: It uses Ktor’s default <a href="https://api.ktor.io/1.3.2/io.ktor.client/-http-client/index.html">HttpClient</a> which will allows us to make HTTP requests. HttpClient is highly configurable: In this particular case we are instructing it to use KotlinxSerializer to deserialize any HTTP response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40bfa5cf4a0b31ac57ff3c4d30ea9a62/href">https://medium.com/media/40bfa5cf4a0b31ac57ff3c4d30ea9a62/href</a></iframe><p><strong>========================================</strong></p><p><strong>NOTE</strong></p><p>KotlinxSerializer uses strict mode parsing by default. This means that the deserialization will fail if it encounters unknown or malformed keys when parsing the JSON payload. In our scenario, this is not an issue because our models are built to capture all the properties of the JSON object they represent.</p><p>The default strict mode parsing behavior can be turned off by explicitly setting the serializer configuration. In earlier versions of KotlinxSerializer, the strict mode parsing behavior was determined by a single constructor argument: strictMode. The current version of KotlinxSerializer, instead, provides three constructor arguments that allow to relax the parsing requirements:</p><ul><li><a href="https://github.com/Kotlin/kotlinx.serialization/blob/ffe216f0293231b09eea24a10aa4bc26ff6d5b90/runtime/commonMain/src/kotlinx/serialization/json/JsonConfiguration.kt#L17">ignoreUnknownKeys</a></li><li><a href="https://github.com/Kotlin/kotlinx.serialization/blob/ffe216f0293231b09eea24a10aa4bc26ff6d5b90/runtime/commonMain/src/kotlinx/serialization/json/JsonConfiguration.kt#L19">isLenient</a></li><li><a href="https://github.com/Kotlin/kotlinx.serialization/blob/ffe216f0293231b09eea24a10aa4bc26ff6d5b90/runtime/commonMain/src/kotlinx/serialization/json/JsonConfiguration.kt#L23">serializeSpecialFloatingPointValues</a></li></ul><p>The default strict mode parsing behavior can be turned off by explicitly setting the serializer configuration as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca2907aacf9176b7d1010c04e3383d65/href">https://medium.com/media/ca2907aacf9176b7d1010c04e3383d65/href</a></iframe><p><strong>========================================</strong></p><p>The setupCall helper method allows us to easily build an url instance given the desired endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8966c13d412ff890aa2582295eef306/href">https://medium.com/media/b8966c13d412ff890aa2582295eef306/href</a></iframe><p>The created url instance will be used by Ktor to make an HTTP call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e595ff28d3a111df40d23e331d9268b5/href">https://medium.com/media/e595ff28d3a111df40d23e331d9268b5/href</a></iframe><p>Ktor’s HttpClient will infer User as the class for deserializing the HTTP response and will try to parse the JSON response and return the result as a List&lt;User&gt; instance.</p><p>Each remaining JSONPlaceholder resource (i.e.: posts, comments, …) can be wrapped using the same approach illustrated above.</p><h3>Conclusion</h3><p>You can find the full code for wrapping JSONPlaceholder <a href="https://github.com/andrea-prearo/JSONPlaceholderKotlin">here</a>.</p><p>In this post we examined how it’s possible to leverage Ktor to nicely wrap a REST API. In particular we saw how we can use Ktor’s HttpClient to make HTTP requests and KotlinxSerializer to deserialize HTTP responses into Kotlin serializable classes.</p><p>In the next post we’re going to take a look at how we can create unit tests for HTTP calls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=778315abfe4d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/granular-engineering/multi-platform-mobile-networking-libraries-with-ktor-778315abfe4d">Multi-platform mobile networking libraries with Ktor</a> was originally published in <a href="https://medium.com/granular-engineering">Granular Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>