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.
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. This post is for both junior and senior developers. And yes, we are going to talk about concepts but stay there, these are some important ones.
API is the acronym for Application Programming Interface. But what does that exactly mean?!
"Application" and "programming" are the easy parts. It is the "Interface" that we need to understand better.
What is an Interface?
An Interface is nothing more than the outside layer, the part that connects with the exterior, keeping the interior safe.
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:
- Graphical Interface: 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.
- Ordering a meal in a restaurant: You place the order and receive the food. It doesn't matter how many cooks they have, the pan color, or the stove brand.
- Sensory System: You don't need to know how your body smells something, it simply does that for you.
The whole idea is based on the concept of inputs and outputs. Given an input, an output is expected, disregard the implementation:
Input | Output | |
Graphical Interface | Button click | Desired action |
Restaurant order | Place the order | Receive the food |
Sensory System | Touch on skin | Related sensation (cold, heat, etc.) |
ATM | Insert a card and password | Receive money |
This concept of input-output-no-matter-the-inside we call black box. There is an important difference here:
- A black box is what we call something that accepts an input and returns an output, without necessarily revealing how it created the output.
- An Interface is how you connect with the system, what is exactly the expected input (a number, two numbers, a string) and how the output will look like (another number, another string). It is like a contract.
Interfaces in OOP
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 official PHP documentation about interfaces but leave a comment if this is a topic you would like to see in another post.
Okay... Can we get back to APIs now?
And here is where the real post begins! Let's get back to the acronym:
Application Programming Interface is a part of the application only accessible via code made by a group of methods with inputs and outputs, doesn't matter their implementation.
Does it make more sense now?
(For the complainers, yeah, I know you can access a REST API with your browser but that is not the intended use of it.)
WordPress's APIs
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): Transients API and Settings API are some examples. The full list of WordPress's APIs is available at https://developer.wordpress.org/apis/.
But why should we use these APIs instead of simply writing something in the database directly or saving a file in the server?
There are many reasons, let's check some of them.
Note: 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.
Separation of concerns
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, a code that creates a product is apart from the code that deals with orders, and that only calls the module responsible for storing data somewhere.
Many years ago, unfortunately, it was common to see PHP applications with several calls to mysqli_real_connect
and similars. Today that is not the reality anymore. In WordPress, for example, we have the wpdb
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.
Readability
We do not write code for machines but for other human beings, 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.
What is easier to understand? This
<?php
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"INSERT INTO `$wpdb->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
)
);
or this?
<?php
update_option( 'my_option', 'value' );
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 update_option()
function does not need to be changed.
Practical Examples
Using WordPress APIs makes life easier. Sometimes, not using them make the project unfeasible.
Files API
This is a classic case. The programmer saves the file using functions like fopen
, fclose
, etc. and everything works fine. The project grows a bit, infrastructure needs to scale and files start to disappear. Let's give a look at some diagrams to understand it better.
Saving directly into the server (with only one web server)
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.
Saving directly into the server (with more than one web server)
Now let's suppose we need another server. In front of the two web servers, we place a load balancer, to split traffic between them.
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.
Saving it somewhere else
Usually, the solution relies on saving the files somewhere else, like an Amazon S3 Bucket, for example. It could be anywhere, the important here is to be a place accessible to all the servers.
How do we fix this?
The solution to this example is simple and makes usage of a plugin.
The most important for us here is that the plugin will only work for the code using WordPress's Files API. It will not be able to change direct calls to fopen
but only calls to $wp_filesystem->put_contents()
or functions that pass through the Files API.
Transients API
If you read the post about the Transients API and the official documentation you'll see that it consists of basically three functions: set_transient()
, get_transient()
, and delete_transient()
. 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: in-memory storage.
Relax, it is not a big deal. When I talked about plugin types, I've talked about drop-ins, one of them being object-cache.php
. 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. Memory access is faster than disk access and, because of that, these programs return things faster than the database.
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, if you are using WordPress's API, a plugin will be enough, it is just a matter of configuring and placing its drop-in 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 the interface you are using remains the same.
WordPress REST API
I've already talked about this topic years ago but it is still useful. If you got here wanting to learn more about WordPress REST API you can check this other post. I'm pretty sure you will like it!
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!
Top comments (4)
Great article Felipe!
Thanks @arlemi !
Wow i liked your way of explanation
Thanks @azlan_syed !