WordPress REST API
Motivation
Although it has a place, exposing a WordPress instance publicly on the web is not my favorite thing 😃 But I like the WordPress backend for easily managing content. Since WordPress has a REST API, it is possible to use it with a custom frontend that consumes the API.
TL;DR
Set permalinks to post name and you can access the API.
Demo
Use this script to get started quickly:
# retrieve WordPress installation which includes SQLite and slugs set to 'Post name'
curl https://joriszwart.nl/poc/wordpress-api/wordpress-pocapidemo.tar.gz --remote-name
tar -xf wordpress-pocapidemo.tar.gz
cd wordpress-pocapidemo
php -S localhost:3000
Then point your browser to http://localhost:3000/ to see the working instance.
Administration can be done by browsing to http://localhost:3000/wp-admin/ and use these credentials:
Username : pocapidemo
Password : pocapidemo
Some API Endpoints
- http://localhost:3000/wp-json/
- http://localhost:3000/wp-json/wp/v2/
- http://localhost:3000/wp-json/wp/v2/pages/
- http://localhost:3000/wp-json/wp/v2/posts/
- http://localhost:3000/wp-json/wp/v2/tags/
Retrieving pages
Using curl:
# retrieve pages
curl http://localhost:3000/wp-json/wp/v2/pages/
Which results in pages.json.
Using JavaScript:
// retrieve pages
const response = await fetch('http://localhost:3000/wp-json/wp/v2/pages/')
const json = await response.json()
console.log(json)
How to build this yourself
- Install Wordpress with or without SQLite 1
- In WordPress go to wp-admin → Settings → Permalinks
- Select Post name. Plain won't work.