Reuse HTTP Client code in iOS app and Linux server?

Hi!

I‘d like to access a third party API from both an iOS app, as well as a Vapor server app, which l am deploying on Heroku.

I wonder what the best approach would be to reuse the client code.

Vapor offers a Client API, but that makes only sense to use in a Vapor app. There is the underlying AsyncHTTPClient API which I am not sure would work in an iOS app, there is URLSession which would make sense for iOS, but seems to have limitations when used in a Vapor app especially on non-Apple platforms, and last not least there is the OpenAPI generator, which requires a OpenAPI document file not available for the particular third party API.

So many choices… :) Which approach would you prefer/recommend these days?

I'd recommend writing an OpenAPI doc for the API and generating the client. You can then use the generated client with URLSession on iOS, and AsyncHTTPClient on the server, as the OpenAPI-generated client already is agnostic to the network library you use.

Would you mind describing the limitations you found? I currently use Vapor's HTTP client, but now that the Static Linux SDK crashes are fixed I want to try Foundation again.

At this point I have a small amount of URLSession based code running seemingly ok on Heroku so far. Of course I stumbled against git push heroku main failing with

remote: /tmp/... : error: cannot find 'URLRequest' in scope

But resolved that quickly after finding I had to add:

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

Fingers crossed :)

1 Like

Thanks, I'll definitely try that! I guess I can probably get away with the subset of the API I actually need :grimacing:

Yes, I've done that many times - instead of hand-writing an HTTP client, I write an OpenAPI doc that covers the APIs I'm interested and then let the tooling generate the rest. And sometimes it even helps to send the OpenAPI doc to the service authors to nudge them towards publishing and maintaining one.

2 Likes

Just wanted to add that openapi repo has an example on how to split clients for server and iOS app using shared yaml file.

2 Likes