Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct pattern for declaring REST service api endpoints in client application?

This is a code style and architectural question. And it is not specific only for iOS or Android. What is the best and the most correct way for declaring\storing REST api's endpoints(urls) in the client app? Let's say I have a client app for some social network or whatever rest service. This service has a lot of different api endpoints: user/login, user/profile, common/list and so on and so forth. There can be a large number of this endpoints. So the question how should I correctly manage this in my client's app? Right now I just declare string constants like this for iOS: static NSString * const kLoginUser = @"user/login", Swift: let loginUser = "user/login" or in Android: "private final String LOGIN_USER = "user/login".

But if the web-service is rather complex there can be 40-50 such string constants or more. And I wondered: maybe I do it in a wrong way, and there are more elegant ways for managing endpoints in REST clients? Any explanations or interesting approaches will be very helpful.

like image 214
MainstreamDeveloper00 Avatar asked Feb 23 '26 07:02

MainstreamDeveloper00


2 Answers

I don't think there's a better way as to hold the endpoint URLs (or unique parts of them) in some constants. If you read them from some configuration files, this is still a constant, that should not change in the runtime.

If you are overwhelmed by a large number of enpoints - group them. Respect the "S" of SOLID - group the related enpoints in one Class. E.g. put the methods accessing user/login, user/profile, user/something_else in a UserServices class, common/a, common/b, common/the_rest in CommonServices. The String constants with the enpoint URLs will be defined in this Services classes.

like image 123
AGV Avatar answered Feb 24 '26 21:02

AGV


The way I generally see it done is to create an enum for your various service calls:

protected enum SpecificRestServiceMethods implements RestServiceMethods{
   EXAMPLE_REST_CALL_ONE("/example/service/examplerestcallone"),
   EXAMPLE_REST_CALL_TWO("/example/service/examplerestcalltwo"),
   //etc etc

   private String path;
   private SpecificRestServiceMethods(String path){
     this.path = path;
   }

   public String getName(){
     return this.name();
   }
   public String getPath(){
     return path;
   }
}

Then just plop that chunk in whatever class is handling your general REST stuff.

like image 45
TechnoloG Avatar answered Feb 24 '26 21:02

TechnoloG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!