Things I Learnt From Android's Swagger Client Codegen
Over the past few days I've had a lot of struggles generating a Swagger-compatible QuestionTime API client for Android.
Quickly for those who aren't aware: Swagger allows you to write API doc for your HTTP web API, and automatically generate clients for multiple platforms and nice HTML documentation for it. I've been waiting for a project to use it in, and in porting QuestionTime to Android, I think I've found the project!
In my discoveries, I've found a few things that I think are important to note before attempting to use Swagger-generated client code for Android:
- It exports by default to Maven-compatible source code. This means that it is only semi-compatible with Android Studio (and its build manager, Gradle) out of the box. If you want to use the Maven source, you'll have to set up a local or remote repository and I didn't want to have to go through this hassle for something I wish to open source one day.
- The latest stable version of swagger-codegen will not compile Android code correctly as it does not implement the singleton pattern for the ApiInvoker. A fix exists, but it won't be brought to the stable version (or into brew) anytime soon which means you'll have to clone swagger-codegen and build the JAR from source.
- Expect to learn a lot about Gradle and how the Android build process works. You'll need to manually copy files from the generated source code to your Android Studio instance, and force overwrite to update each time. Additionally, you'll have to graft the dependencies from the build.gradle file. If you get dex errors, remove the Apache httpclient as a dependency (as it's not needed) and exclude some metadata files in the build.gradle.
- The model classes you define in your API doc must map exactly to the response you receive from the API, otherwise the Volley request will not get resolved and you'll get a mysterious Concurrent TimeoutError. I found this out the hard way, after tinkering for at least twelve hours and learning how Futures work in Java.
Overall it's been a frustrating but rewarding experience, and I've ended up with generated client code that is type safe, handles all serialisation and deserialisation, and abstracts and simplifies the API methods which will increase the agility of my project.
If you want some real-world examples of how to write to the API doc spec, check out the inline API spec I've added for QuestionTime here.