Join Morten Rand-Hendriksen for an in-depth discussion in this video Things to consider when extending the API response, part of WordPress: REST API.
- [Instructor] The default response from the REST API is pretty comprehensive, and with the long list of links at the bottom of each post object and the embedding feature, you're able to get to most content with ease. Even so, there are times when you need some additional content added to the response to add a new content type or feature to the site or app you're building. In this chapter, we'll explore how to extend the API response by adding new custom post types, new custom taxonomies, and most importantly, new fields in the response itself.
What you learn here will enable you to extend the API to work with pretty much any custom setup you choose to create for your WordPress installation. Before we start, let me briefly address an important principle when working with APIs. Here's the short version. Existing APIs should be extended, not modified. By this I mean anytime you want to change the API output to fit your needs, add new fields or features rather than modifying existing ones. The reason for this has to do with resilience, as explained in the documentation for the API.
"The API exposes many fields on API responses, "including things you might not need, or might not fit "into how your site works. "While it's tempting to modify or remove fields "from responses, this will cause problems with API clients "that expect expect standard responses. "This includes things like mobile clients, "or third party tools that help you manage your site. "Adding fields is not dangerous, "so if you need to modify data, it's much better "to duplicate the field instead with your modified data.
"Removing fields is never encouraged; "if you need to get back a smaller subset of data, "work with contexts instead, "and consider making your own context." And you'll remember, context is the first property in the API index for each of the routes. Searching online, you'll find countless articles and tutorials explaining how to modify or remove items from the API response. I urge you to resist this temptation. If you need a custom response, add it to the API to ensure the standard expected response is always there.
That's how we keep the web resilient and future proof the services and solutions we build.
- Using a REST client to communicate with a REST API
- Reviewing available routes, endpoints, and arguments
- Adding custom post types and taxonomies
- Altering the API response
- Using PHP for resiliency
- Passing info using wp_localize_script()
- Setting up a REST API request through AJAX
- Outputting selected post data to the front end
- Formatting post data to match a theme
- Triggering AJAX for an infinite scroll effect
- Using AJAX to load subsequent responses