r/AskProgramming • u/cellwall-999 • Mar 26 '20
APIs Explained ...
I dunno but I don't understand APIs fluently. Does anyone know of an informative article or perhaps a website or just personally explain to me frankly wtf APIs are an why we need them ...
Edit: Thanks everyone for your empathetic contributions. Guess what; I have a better understanding of APIs now than I did before.
53
Upvotes
2
u/Dparse Mar 26 '20 edited Mar 27 '20
OK something I'm not really seeing other people say is that there is another, more general meaning of the term API. Like everyone says it stands for Application Programming Interface, but 'application' here does not necessarily mean two different programs, perhaps operating on different servers.
API can also refer to the interface that a class or module makes available for other parts of the code in the project to use. You might say "The API of my user class allows editing the user's name, but not their address." In this sense the API is the line between something's internals - like the methods that a class uses privately to handle its business - and absolutely everything else, which is external. By tightly controlling your API and what it provides you can have perfect control over how the internals are operated and modified.
As a concrete example, imagine a class User with public fields for name and address, like my example above. That might look like this in pseudocode:
However since these strings are public, any code that is using Harry could very easily change Harry's address. Now maybe that's what you want to do if Harry is in a
UpdateUserAddressmethod, but other methods that shouldn't be touching Harry's address could touch it, and they shouldn't be allowed.Let's imagine you want to model the logic "Addresses must be in the United States" and you have a method called
CheckAddressInUnitedStatesthat will verify exactly that. With User's API the way it is, even the places that should update addresses will be required to remember to call yourCheckmethod, or invalid addresses might sneak in.Imagine if instead User looked like this.
Now, the address is private, and other parts of the code cannot read or write it. We have instead provided an API to address, and we can enforce our logic within that API. Now, if someone tries to set Harry's address to something that is outside the US, the
ifcondition will be false and the newAddress will not be saved.I've omitted
getAddressbecause its implementation starts to beg the question of whether or not you should have anAddressclass, which is a broader discussion I don't want to get in to.