joriszwart.nl

I code dreams™

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

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

  1. Install Wordpress with or without SQLite 1
  2. In WordPress go to wp-adminSettingsPermalinks
  3. Select Post name. Plain won’t work.

Notes


  1. Unlike a lot of others, I’m a proponent of using SQLite in production, but your mileage may vary. Especially with write-intensive applications.