What is an API?
Tags: api, wordpress, php, beginners
Published: 2022-06-30 00:11:49

<!-- wp:paragraph -->
<p>Do you know what is an API? Why is it important to use your favorite framework's APIs? Have you already heard about interfaces and black boxes? In this post, we will talk about all these topics with examples.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I was going to write about the reasons why you should use WordPress's APIs but I had to go back to so many concepts that we have to start talking about what is an API. <strong>This post is for both junior and senior developers.</strong> And yes, we are going to talk about <em>concepts</em> but stay there, these are some important ones.</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>API is the acronym for <strong>Application Programming Interface</strong>. But what does that exactly mean?!</p></blockquote>
<!-- /wp:quote -->

<!-- wp:image {"align":"center","id":2025,"sizeSlug":"medium","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-medium"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/confused-macgyver.png"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/confused-macgyver-300x225.png" alt="MacGyver confuso com a frase &quot;I don't understand&quot; escrita" class="wp-image-2025"/></a></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>"Application" and "programming" are the easy parts. It is the "Interface" that we need to understand better.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>What is an <em>Interface</em>?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>An Interface is nothing more than the outside layer, <strong>the part that connects with the exterior</strong>, keeping the interior safe.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We deal with this concept every day and if that wasn't possible we would freak out. Imagine if you had to know all the ins and outs of everything surrounding you! Some interface examples:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>Graphical Interface:</strong> You click, the program executes. You don't need to know how it does, if you click and it does what you want that is all that matters.</li><li><strong>Ordering a meal in a restaurant:</strong> You place the order and receive the food. It doesn't matter how many cooks they have, the pan color, or the stove brand.</li><li><strong>Sensory System:</strong> You don't need to know how your body <em>smells</em> something, it simply does that for you.</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center","id":2008,"sizeSlug":"full","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-full"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/caixa-eletronico.gif"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/caixa-eletronico.gif" alt="Mulher chegando a um caixa eletrônico aberto, com um homem sentado dentro fazendo contas para dar o dinheiro." class="wp-image-2008"/></a><figcaption>Insert a card and a password, and receive the money. That is all that needs to happen. It doesn't matter if it is a machine or a guy with a calculator.</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>The whole idea is based on the concept of <em>inputs</em> and <em>outputs</em>. Given an input, an output is expected, disregard the implementation:</p>
<!-- /wp:paragraph -->

<!-- wp:table {"className":"is-style-stripes"} -->
<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td></td><td><strong>Input</strong></td><td><strong>Output</strong></td></tr><tr><td>Graphical Interface</td><td>Button click</td><td>Desired action</td></tr><tr><td>Restaurant order</td><td>Place the order</td><td>Receive the food</td></tr><tr><td>Sensory System</td><td>Touch on skin</td><td>Related sensation (cold, heat, etc.)</td></tr><tr><td>ATM</td><td>Insert a card and password</td><td>Receive money</td></tr></tbody></table></figure>
<!-- /wp:table -->

<!-- wp:paragraph -->
<p>This concept of input-output-no-matter-the-inside we call <strong>black box</strong>. There is an important difference here:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>A black box is what we call something that accepts an input and returns an output</strong>, without necessarily revealing how it created the output.</li><li><strong>An Interface is how you connect with the system</strong>, what is exactly the expected input (a number, two numbers, a string) and how the output will look like (another number, another string). <em>It is like a contract.</em></li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center","id":2061,"sizeSlug":"full","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-full"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/black-box-and-interface.jpg"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/black-box-and-interface.jpg" alt="" class="wp-image-2061"/></a></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Interfaces in OOP</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Here I have to open a quick parenthesis. Interfaces are also something very important in Object-Oriented Programming. The idea is exactly the same: if a class declares it implements a certain interface, it is required to implement all the interface's methods. I'll leave here the <a href="https://www.php.net/manual/en/language.oop5.interfaces.php" target="_blank" rel="noreferrer noopener">official PHP documentation about interfaces</a> but leave a comment if this is a topic you would like to see in another post.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Okay... Can we get back to APIs now?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>And here is where the real post begins! Let's get back to the acronym:</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p><strong>Application</strong> <strong>Programming</strong> <strong>Interface</strong> is a <em>part of the application only accessible via code made by a group of methods with inputs and outputs, doesn't matter their implementation</em>.</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>Does it make more sense now?</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":2063,"sizeSlug":"medium","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-medium"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/now-i-see-now-i-get-it.jpg"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/now-i-see-now-i-get-it-300x167.jpg" alt="" class="wp-image-2063"/></a></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>(For the complainers, yeah, I know you can access a REST API with your browser but that is not the intended use of it.)</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>WordPress's APIs</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>When I had the idea to write this post, I was going to talk about how important it is to use WordPress's internal APIs. WP has lots of these APIs, we've already talked about some of them here (in Portuguese):  <a href="https://felipeelia.com.br/cache-facil-no-wordpress-transients-api/">Transients API</a> and <a href="https://felipeelia.com.br/como-criar-uma-tela-de-configuracao-para-o-seu-plugin-wordpress-com-a-settings-api-parte-1/">Settings API</a> are some examples. The full list of WordPress's APIs is available at <a href="https://developer.wordpress.org/apis/">https://developer.wordpress.org/apis/</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>But why should we use these APIs instead of simply writing something in the database directly or saving a file in the server?</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>There are many reasons, let's check some of them.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Note:</strong> these concepts are not isolated but rather complementary. Also, I did not try to cover all the possible aspects, so feel free to explore any other aspect in the comments section.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Separation of concerns</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This is a principle that aims to split the application into modules, each one responsible for just one thing. These modules communicate with each other using — you guessed it — interfaces. This way, <strong>a code that creates a product is apart from the code that deals with orders</strong>, and that only <em>calls</em> the module responsible for storing data somewhere.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Many years ago, unfortunately, it was common to see PHP applications with several calls to <code>mysqli_real_connect</code> and similars. Today that is not the reality anymore. In WordPress, for example, we have the <code>wpdb</code> class, other frameworks use ORM but every time it is necessary to store/save some data there is an abstraction layer we can count with.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":2039,"sizeSlug":"full","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-full"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/ruptura.gif"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/ruptura.gif" alt="" class="wp-image-2039"/></a><figcaption>The <em>Severance</em> TV Series takes separation of concerns to a WHOLE DIFFERENT level.</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Readability</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><strong>We do not write code for machines but for other human beings</strong>, after all, we say "Code is poetry" for a reason. That said, it is important to look at a code for the first time and understand what it does.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>What is easier to understand? This</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;?php
global $wpdb;
$wpdb-&gt;query(
	$wpdb-&gt;prepare(
		"INSERT INTO `$wpdb-&gt;options` (`option_name`, `option_value`, `autoload`)
			VALUES (%s, %s, %s)
			ON DUPLICATE KEY
			UPDATE
				`option_name` = VALUES(`option_name`),
				`option_value` = VALUES(`option_value`),
				`autoload` = VALUES(`autoload`)", 
		$option,
		$serialized_value,
		$autoload
	)
);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>or this?</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;?php
update_option( 'my_option', 'value' );</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The second option, right? It is easy to understand we are saving an option and if we want to use any other storage mechanism like Redis or Memcached (more about this below), the part of the software calling the <code>update_option()</code> function does not need to be changed.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":2040,"width":576,"height":323,"sizeSlug":"full","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-full is-resized"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/code-is-poetry.jpg"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/code-is-poetry.jpg" alt="" class="wp-image-2040" width="576" height="323"/></a><figcaption>Code is Poetry!</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Practical Examples</h2>
<!-- /wp:heading -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Using WordPress APIs makes life easier. Sometimes, not using them make the project unfeasible.</p></blockquote>
<!-- /wp:quote -->

<!-- wp:heading -->
<h2>Files API</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This is a classic case. The programmer saves the file using functions like <code>fopen</code>, <code>fclose</code>, etc. and everything works fine. The project grows a bit, <strong>infrastructure needs to scale and files start to disappear</strong>. Let's give a look at some diagrams to understand it better.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Saving directly into the server (with only one web server)</h3>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":2066,"sizeSlug":"full","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-full"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/wp-files-api-part-1-saving-directly-into-the-server.jpg"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/wp-files-api-part-1-saving-directly-into-the-server.jpg" alt="" class="wp-image-2066"/></a></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>So far, so good. The admin user sent the file to the single server and, when the user visits the site, the file will be there.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Saving directly into the server (with more than one web server)</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now let's suppose we need another server. In front of the two web servers, we place a <em>load balancer</em>, to split traffic between them.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If we save the file directly into the server, it will be stored only in the server where the admin user uploaded the file, not being found every time the requests are sent to the other web server.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":2067,"sizeSlug":"full","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-full"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/wp-files-api-part-2-saving-directly-into-the-server.jpg"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/wp-files-api-part-2-saving-directly-into-the-server.jpg" alt="" class="wp-image-2067"/></a></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>Saving it somewhere else</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Usually, the solution relies on saving the files somewhere else, like an <a href="https://aws.amazon.com/s3/" target="_blank" rel="noreferrer noopener">Amazon S3 Bucket</a>, for example. It could be anywhere, the important here is to be a place accessible to all the servers.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":2069,"sizeSlug":"full","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-full"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/wp-files-api-part-3-saving-into-amazon-s3.jpg"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/wp-files-api-part-3-saving-into-amazon-s3.jpg" alt="" class="wp-image-2069"/></a></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>How do we fix this?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The solution to this example is simple and makes usage of a <a href="https://github.com/humanmade/S3-Uploads">plugin</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The most important for us here is that <strong>the plugin will only work for the code using WordPress's Files API</strong>. It will not be able to change direct calls to <code>fopen</code> but only calls to <code>$wp_filesystem->put_contents()</code> or functions that pass through the Files API.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Transients API</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you read the <a href="https://felipeelia.com.br/cache-facil-no-wordpress-transients-api/">post about the Transients API</a> and the <a href="https://developer.wordpress.org/apis/handbook/transients/#function-reference">official documentation</a> you'll see that it consists of basically three functions: <code>set_transient()</code>, <code>get_transient()</code>, and <code>delete_transient()</code>. You could quickly implement three functions to store, get, and delete values from the database but you would be losing one of the most used pieces of infrastructure to improve performance: <strong>in-memory storage</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Relax, it is not a big deal. When I talked about <a href="https://felipeelia.com.br/tipos-de-plugin-do-wordpress/">plugin types</a>, I've talked about <em>drop-ins</em>, one of them being <code>object-cache.php</code>. With it, it is possible to use software like Redis or Memcached to store things in memory, instead of going to the disk every time. <strong>Memory access is faster than disk access</strong> and, because of that, these programs return things faster than the database.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you are storing things in your database directly, adding something like these programs to your infrastructure will make no difference. On the other hand, <strong>if you are using WordPress's API, a plugin will be enough</strong>, it is just a matter of configuring and placing its <em>drop-in</em> and things will automatically work. If you want to change between Redis and Memcached you won't need to worry too, as the implementation will change but <em>the interface you are using remains the same</em>.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":2048,"width":480,"height":216,"sizeSlug":"full","linkDestination":"media"} -->
<figure class="wp-block-image aligncenter size-full is-resized"><a href="https://felipeelia.com.br/wp-content/uploads/2022/06/redis-object-cache-plugin.png"><img src="https://felipeelia.com.br/wp-content/uploads/2022/06/redis-object-cache-plugin.png" alt="" class="wp-image-2048" width="480" height="216"/></a><figcaption>Here in the blog, I use the <a href="https://br.wordpress.org/plugins/redis-cache/" target="_blank" rel="noreferrer noopener">Redis Object Cache</a> plugin</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>WordPress REST API</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I've already talked about this topic years ago but it is still useful. If you got here wanting to learn more about <a href="https://felipeelia.com.br/a-api-rest-do-wordpress/">WordPress REST API</a> you can check this other post. I'm pretty sure you will like it!</p>
<!-- /wp:paragraph -->

<!-- wp:separator -->
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<!-- /wp:separator -->

<!-- wp:paragraph -->
<p>This is a giant post, I know. If you can share it on your social networks, subscribe to the newsletter, and leave a comment you help me a lot. THANK YOU!</p>
<!-- /wp:paragraph -->