Software Engineering in WordPress, PHP, and Backend Development

Tag: REST API

Asynchronous Methods and Headers: Just Working Isn’t Good Enough

When sending asynchronous requests to a WordPress back-end, which may be a REST API or an Ajax callback, it’s helpful to know what headers to specify when sending said data.

Since I recently shared another post about idempotency in REST API design and since asynchronous calls are more common than they have been in the past, I thought it useful to share when to use what type of headers when making said requests.

If you’re working with WordPress in some capacity – be it a headless state or working on processing Ajax calls – then it’s useful indicate how your data is being sent and in what format the data is being sent. Ultimately, your asynchronous methods and headers need to do more than just work.

That is, it’s not enough for it to simply be sent and received. Instead, the data should be sent in a format congruent with what the backend service expects. If anything, future you will thank you. To make it even more relevant, this is an opportunity to keep our code as clean as possible.


Asynchronous Methods and Headers

When creating an Ajax request in WordPress using modern, vanilla JavaScript the request will likely look something like this:

fetch(tmAcmePlugin.ajaxurl, {
    method: 'POST',
    body: data,
    credentials: 'same-origin',
    headers: new Headers({
        'Content-Type': 'application/json',
    }),
})

Notice here I’m specifying the headers as part of the request which isn’t something we’ve historically done. In this example, I’m using application/json.

It’s also common to send form data across the wire, too. And if you do that, then your request will look something like this:

fetch(tmAcmePlugin.ajaxurl, {
    method: 'POST',
    body: data,
    credentials: 'same-origin',
    headers: new Headers({
        'Content-Type': 'application/x-www-form-urlencoded',
    }),
})

Obviously, know which type of header to send and when is important. As obvious as it seems, these are the guidelines I recommend when working in the context of WordPress-centric applications.

  • Use application/json whenever you’re sending a payload that’s structured as JSON. Whenever you’re receiving the data on the server, you’ll need to use json_decode or your language’s equivalent to parse the data.
  • Use application/x-www-form-urlencoded whenever you’re sending a payload that comes from data being sent from a form element or in a string of key/value pairs such as key_one=value_one&key_two=value_two. Typically, this will be received in a POST request.

Again, however you specify the method and the header, the data will still be sent but how you manage it on the server may not match up to what’s expected.


If someone else – either someone with whom you work or just future you – reads the client-side code and the server-side code and what’s sent doesn’t match, it’s going to create an entire set of circumstances of detangling what’s been done and something that’s completely unavoidable.

Understanding Idempotency in REST API Design

This week, I read a great article relevant to anyone developing applications that include a REST API. It’s titled Every Programmer Should Know #1: Idempotency.

First, note that idempotence is:

The property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.

wikipedia

In other words, in the context of REST APIs, the result of making a request shouldn’t change the state of the application more than once. That is, you make the same request multiple times, there should be no side effects such that the same result is sent each time.

Or, perhaps even more simply, if the same request is sent more than once, it’ll only be processed once.


Secondly, the crux of the article has a great breakdown of the various methods that should exist in a REST API:

  1. GET Method:
    The GET method is used to retrieve a resource from the server. It is an idempotent method because retrieving the same resource multiple times will not change the resource itself or cause any side effects on the server.
  2. PUT Method:
    The PUT method is used to update a resource on the server. It is idempotent because sending the same request multiple times will result in the same resource state as if the request had only been sent once. For example, if you send a PUT request to update a user’s email address with the same new email address multiple times, the user’s email address will only be updated once.
  3. DELETE Method:
    The DELETE method is used to delete a resource from the server. It is idempotent because deleting a resource multiple times will have the same result as deleting it only once. If the resource has already been deleted, sending a DELETE request for the same resource will not result in any changes.
  4. POST Method:
    The POST method is used to create a new resource on the server or to submit data to be processed. It is not idempotent because sending the same request multiple times will create multiple resources or submit the same data multiple times, resulting in different outcomes.

And keeping this in mind is very helpful when designing an API.


Ultimately, I share this because the article does a great job of breaking down the concepts of idempotency in REST API design and the supporting application. And it’s a good reminder to have on hand whenever I’m – or you, whoever you are ::s

How To Build Headless WordPress Applications with a REST API

Since both the REST API and Headless WordPress applications are now mainstream within the WordPress development economy, it’s likely developers have a standard set of tools they like to use when working on these types of projects.

Yours truly not excepted.

And though I’m not making the case that my set of tools should be the standard, I have a set of tools that I’ve found and consistently use when building headless WordPress applications with a REST API.

  • MailHog
  • Insomnia
  • JWT Auth

Though this isn’t in any particular order, I’ll outline them here, how I use them, and explain how they help with login and authentication, testing custom API endpoints, and reviewing emails sent from the local development environments.

Continue reading

Bankruptcy on Block Editor Blocks (But It’s Not What You Think)

In August 2022, I started a series on Learning to Build Block Editor Blocks and I continued it for several months. The last thing I wrote in the series was the following:

So as I continue with the series, we’re first going to look at what’s required to implement a custom block that includes:

  • a heading,
  • a paragraph,
  • and an input field to help guide the ultimate output.

We’ll continue to use the customization options we’ve outlined in this post and show how we can apply them to what the user provides and how to ignore them for what we, as the developer, provide.

After that, we’ll look at adding an input to the frontend of the site as well as incorporating a SlotFill.

And though I had intentions to follow through starting at the beginning of the new year, I obviously never followed through with the series. In all of the years that I’ve been writing, sharing code, and generally participating in all things PHP, WordPress, and development, I don’t think I’ve ever simply declared bankruptcy on an actual series or even just on the consistency of blogging in general.

But that’s what I’m doing in this post.

Continue reading

WordPress and Data Ownership, Social Networks and Privacy

I try to be pretty open-minded about most things. That is, I try not to be legalistic or dogmatic about any particular idea. If something comes along that contradicts something I hold true or near and dear, I’m willing to evaluate the evidence and see if it reinforces or challenges what I believe.

Admittedly, there are people who are better at it than I am but I do my best.

But one thing I absolutely cannot get passed – and this is something becoming more and more prevalent the older I get and the more I work in software, specifically in open source – is the idea of data ownership.

And I believe there’s a direct result between what we’re able to do with WordPress and data ownership that can positively impact the type of solutions we release and we’ve yet to even realize we can build.

Continue reading

© 2024 Tom McFarlin

Theme by Anders NorenUp ↑