Structuring Swift API endpoints

We generally maintain service constants in a constants file, changing the endpoints for environments like development, staging and production. Unfortunately, this process is prone to human error when pushing builds to the store or doing an adhoc release. To avoid this, we can construct baseURL per the environments, as shown below.

Then you can add application-related functions in extensions like this:

USING AN ENVIRONMENT IN ACTION:

We can maintain the respective environments using the “Debug” setting from build settings. To do so, we will use the preprocessor macro #if DEBUG and set the environment to “Development.” We can change the environment to “Staging” or “Production” under #else.

The endpoints can be managed as seen below. We can even group multiple endpoints for that fall under a specific functionality. For example, user related API’s can be grouped under “struct User” and can be accessed as “structName.method”.

Usage:

We can see how the Paths flow visually in Xcode:

A sample ServiceConstants.swift file is available to view by clicking the following link:

https://github.com/appitventures/IOS-Blog/blob/master/ServiceConstants.swift

For more details on how to maintain environments from project targets and schemes, refer to this blog:

https://appitventures.com/blog/setting-xcode-targets-create-multiple-ios-builds-different-api-environments/

--

--