djibouti33
djibouti33

Reputation: 12132

Managing API endpoints as constants

I've inherited an iPhone app that has a file containing all code necessary to perform API calls to our server (ServerRequests.h/m).

All endpoints for the API are buried within the various methods, and I'm looking for a way to refactor these endpoints out into their own separate file, or at the very least declared constants at the top of this file.

The problem is portions of the API endpoints are variable, such as user_id, photo_id, etc.

Am I amble to store a format string as constant and then have the variable portions replaced at a later time?

If not, do you have any suggestions about how to manage my API endpoints in a better way than just strewing them all throughout a file?

Upvotes: 1

Views: 653

Answers (1)

Art Swri
Art Swri

Reputation: 2804

If I understand your need, something like this might work for you:

#define SOME_ENDPOINT @"what/ever/%@/you/need"

At the point of use, you use string formatting to get the final string:

[NSString stringWithFormat:SOME_ENDPOINT, user_id, ...];

IOW the majority of the string is stored in a constant that is a template used as the format spec for formatting the final string.

Is that what you want? Or need something 'fancier'? There is a feature of Python that I miss in Obj-C - you can have 'named' specifiers in the format like @"some/%(user_id)s/etc/etc/" and when you perform the formatting, you supply a dict(ionary). The 'user_id' spec is used as a key to find the associated value, which is then formatted (e.g., using the 's' spec in my example. Have not found a similar feature in Obj-C tho.

Upvotes: 2

Related Questions