-2

I'm currently writing some code to interact with an API that doesn't have any official libraries. The provider has given me two sets of credentials - one for testing and one for production.

I'm wondering what the best practice is for choosing which set of credentials to use.

Should I assume Testing (or Production) by default and have a function like setEnvironment($env) to change it as needed?

Would it be better to have two different classes to choose from when first setting up the connection like new Api\Testing(); and new Api\Production();

Or should the API use credentials provided by the rest of the application like new Api($username, $password);

  • 1
    What would be the consequences of connecting to production instead of testing? Pretty bad. What would be the consequences of connecting to testing instead of production? Also pretty bad. So you should not allow yourself to make either mistake. Don't have a default. – user253751 Oct 1 at 18:12
4

If the question is just "where do I connect to" and "how do I authenticate", I say you should let the base URL and credentials be provided as configuration. That could mean they are passed in as constructor parameters, loaded from .properties files, read from environment variables, or any number of other options, depending on what is appropriate.

I would not use a separate class unless there is a difference in behavior - e.g. if there is ever a second version of the API.

If your code will be consumed by other code, I would lean towards constructor parameters, since they are very unobtrusive in comparison.

I would not have default values that will be overridden in one case. Whether it is calling test or prod is something that the consuming code needs to be absolutely sure about, and hiding it in default values may well hinder that. Having default values also means that your code (as opposed to the code using your API client) would have to be aware of the credentials, which means that you will need to be more careful about who sees your code.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.