I am currently creating a library that is a wrapper for an online API. The obvious end goal is to make it as easy for others to use as possible. As such I am trying to determine the best approach when it comes to common parameters for the API.
In my current situation there are 3 (consumer key, consumer secret, and and authorization token). They are essentially needed in every API call. My question is should I make these 3 parameters required for each method or is there a better way.
I see my current options as being:
-
Place the parameters in each method call
public ApiObject callMethod(String consumerKey, String consumerSecret, String token, ...)
This one seems reasonable, but seems awfully repetitive to me.
-
Create a singleton class that the user must initialize before calling any api methods. This seems wrong, and would essentially limit them to accessing one account at a time via the API (which may be reasonable, I dunno).
-
Make them place them in a properties file in their project. That way I can load the properties that way and store them. This seems similar to the singleton to me, but they would not have to explicitly call something to initialize these values.
Is there another option I am not seeing, or a more common practice in this situation that I should be following?
I think what Telastyn is suggesting is
public class ConsumerContext { string key; string secret; string token; }
public ApiObject callMethod(ConsumerContext, ...)
This is sometimes a way of providing locale information as well – add it to the context.
2
None of the above!
As part of the API have a context or connection or whatever is most appropriate. Have the consumer specify these tokens on constructing, then the method calls are instance methods on the context.
6
This is merely to demonstrate with formatting what I think Telastyn was describing…
public class ConsumerContext
(
prop string key
prop string secret
prop string token
# default ctor
public ConsumerContext(){}
# parameterized ctor
public ConsumerContext(string key, string secret, string token)
{
this.key = key
this.secret = secret
this.token = token
}
public void FooWrapper(fooApiSpecificParamList)
{
api.foo(this.key, this.secret, this.token, fooApiSpecificParamList)
}
public void BarWrapper(barApiSpecificParamList)
{
api.bar(this.key, this.secret, this.token, barApiSpecificParamList)
}
}
2
I can see two ways:
- coalesce all your parameters into a single context object, at the API client side. Each time you call your API, pass the context object as parameter.
- use a similar context object, but store it at the API side. Give the client a token that identifies the context object and ask the API client to pass it each time it calls the API. This is useful if you cannot easily send objects to the API (e.g. HTTP API)