If you’re looking to setup a nice URI structure for an API endpoint within WordPress, there are a few approaches to accomplish this.
Approaches
1. Add a literal directory to your docroot and load WordPress outside of a typical index request with wp-load.php. This can cause some headaches and you have code residing outside of WordPress to maintain.
2. Create a page and assign an API endpoint page template. This is not too desirable as other editors/admins can easily touch this page.
3. Create an endpoint with a rewrite rule.
Example
I created an example API endpoint to serve up pug bombs from the ever awesome Pug Bomb API. You can download the fully functional API endpoint plugin here. Here’s the code:
Once you activate the plugin, you will need to visit the Permalinks page to flush the rewrite rules.
Overview
Here’s a brief overview of how this works:
– A rewrite rule is added for /api/pugs/{N_PUGS} and passes a hidden query var __api and number of pugs.
– An api request sniffer watches for the query variable __api and sends the request to be processed and subsequently kills the rest of the WordPress processes.
– The pug bomb request is validated and processed a JSON response is sent to the browser with an error or pug bomb goodness.
Feel free to ping me if you have any questions. Enjoy the script and hug a pug!