API Wrapper – How to Handle Many Arguments in an API Wrapper

apiPHPrest

I'm writing a PHP API wrapper for a third party API. I want to make all the methods consistent, but I'm not sure how to handle the number of arguments some API routes accept. One API request accepts up to 30 arguments. Obviously, it would be unwieldy to list each argument as a parameter on the method. Currently, I'm writing it to accept the required arguments as method paramaters, while all the optional ones are accepted in a final "additionalOptions" array.

public function sampleApiMethod($reqVal1, $reqVal2, $additionalOptions) {
    //Method Code
}

Unfortunately, there are API requests that have only optional arguments. In this case, either the only parameter is the array of options, or the method has individual parameters for optional arguments. When only passing an array, the method is consistent with the other methods, but it's not the most intuitive. With the latter option, I lose the consistent structure. Is there any sort of best practice or structure for an API wrapper that I should follow to try to have a consistent developer usage experience?

Best Answer

There are a couple good ways to handle this and it really comes down to your personal preference and just how complex your API interface really is. For a simple complexity interface I would increase the number of functions to be just the most specific calls to a given set of use cases. You might be lucky and find that if there are only 10 different use case actions where an actor might need different combinations of required and optional arguments then one might just create ten different functions for this.

This may not be the best solution however if there are a large combination of arguments and use cases to consider.

Check out the Builder Pattern

The premise of the Builder pattern is that your object class will contain a special builder class object that can construct your object through function calls that return the same object. This allows for fluid code that is much more verbose and clear to a client of the API. This can be much more useful in representing a function's parameters than an extremely long list of arguments and prevents the common problem of a client accidentally mismatching arguments. The client is forced to be verbose in building his arguments.

sendPizza ( pizzaBuilder->buildPeppers()->buildSausage()->etc...)

One is able to instantly look at the client code and decipher the breadth of arguments passed to sendPizza.

Related Topic