SlideShare a Scribd company logo
1 of 24
Christina Garofalo @ WordCamp Montréal 2023 | Nov 8, 2023
Old WP REST API, New Tricks
How to create a custom REST API endpoint and make cool stuff
I’ve always had a knack for figuring things out. I have no
formal training in computer sciences, but lots of hands
on experience.
I’m self-taught
I’ve been with the agency for 6 years, and I work with a
great collaborative team.
I’ve worked with WordPress for about 10 years
I joined in person at WCEU Athens 2023. Anyone can
contribute. No programming knowledge required!
I’m on the WordPress Documentation Team
This is my first talk at a WordCamp
I’ll happily chat and answer any questions you may have.
Bonjour/Hi!
Christina Garofalo
Senior WordPress Developer
Today’s Agenda 1 Introduction
2 What is a REST API?
3 Out-of-the-Box API Endpoints
4 Let’s Build a Custom Endpoint!
5 Security
6 Q & A
Introduction
The WordPress REST API
➔ WordPress introduced the REST API in version 4.7 (2016) and
it became the foundation for the WordPress block editor.
➔ The REST API sends and receives data in JSON format,
making it easy to integrate into web applications.
➔ With the REST API, it is possible to do things such as build an
entirely new admin experience, a completely new interactive
front end experience, or create entirely new applications with
your WordPress content.
➔ The REST API is one of many WordPress APIs. They are listed
here: https://codex.wordpress.org/WordPress_APIs
What is a REST API?
What can it do?
REST APIs have these methods
PUT
GET POST DELETE
Application Programing Interface
REpresentational State Transfer
A software architecture that imposes conditions of how an API should work.
A standardized structure.
Additional information
HTTP Headers
Parameters
Data
Out-of-the-box
WordPress API Endpoints
WordPress API Endpoints
All WordPress installations have standard endpoints baked in that can
be used to manipulate:
There is extensive documentation available about the
endpoints and all of the parameters found
in the REST API handbook.
https://developer.wordpress.org/rest-api/
➔ Posts
➔ Media
➔ Users
➔ Tags
➔ Pages
➔ Comments
➔ Taxonomies
➔ Post Types
➔ Post Statuses
➔ General Blog Settings
APIs are not intended for humans to ‘read’.
APIs make it possible for systems to talk to each other.
Use Firefox or Chrome with the JSONvue extension to see
structured JSON in your browser. Otherwise, it’s just a wall of text.
Other tools can be used to test endpoints, such as Postman or
Insomnia. These apps are more useful for testing endpoints with
authentication, POST, PUT and DELETE methods.
No Humans Allowed!
The most basic WordPress REST API endpoint
is simply /wp-json.
This will return basic information about the
WordPress installation.
https://wcmtl.local/wp-json/
{
name: "WordCamp Montreal API Demo",
description: "A site demonstrating the REST API",
url: "http://wcmtl.local",
home: "http://wcmtl.local",
gmt_offset: -4,
timezone_string: "America/Toronto",
namespaces:
[
"oembed/1.0",
"wcmtl/v1",
"wp/v2",
"wp-site-health/v1",
"wp-block-editor/v1"
],
authentication:
{
application-passwords:
{
endpoints:
{
authorization:
"http://wcmtl.local/wp-admin/
authorize-application.php"
}
}
},
Basic Endpoint
[
{
id: 1,
date: "2023-10-24T18:00:33",
date_gmt: "2023-10-24T18:00:33",
guid:
{
rendered: "http://wcmtl.local/?p=1"
},
modified: "2023-10-24T18:00:33",
modified_gmt: "2023-10-24T18:00:33",
slug: "hello-world",
status: "publish",
type: "post",
link: "http://wcmtl.local/hello-world/",
title:
{
rendered: "Hello world!"
},
content:
{
rendered: " <p>Welcome to WordPress. This
is your first post. Edit or delete it, then
start writing!</p> ",
protected: false
},
excerpt:
{
rendered: "<p>Welcome to WordPress. This is
your first post. Edit or delete it, then
start writing!</p> ",
protected: false
/wp-json/wp/v2/posts
This endpoint will return a list of all posts.
It can also take parameters (aka arguments):
/wp-json/wp/v2/posts?sticky=true
https://wcmtl.local/wp-json/wp/v2/posts
https://wcmtl.local/wp-json/wp/v2/posts?sticky=true
An Example: Posts Endpoint
[
{
id: 1,
name: "Christina",
url: "http://wcmtl.local",
description: "",
link: "https://wcmtl.local/author/christina/",
slug: "christina",
avatar_urls:
{
24:
"https://secure.gravatar.com/avatar/575
63c471581211b8818c051015343c5?s=24&d=mm
&r=g",
48:
"https://secure.gravatar.com/avatar/575
63c471581211b8818c051015343c5?s=48&d=mm
&r=g",
96:
"https://secure.gravatar.com/avatar/575
63c471581211b8818c051015343c5?s=96&d=mm
&r=g"
},
/wp-json/wp/v2/users
The users endpoint, which is a public endpoint,
will return a list of all users subscribed to your
site, regardless of role. It does not return the
roles associated with the users, but it does return
usernames and IDs, which can be used to figure
out which account might be an admin and could
be an attack vector for the ne’er-do-wells out
there looking to gain access to your site. (More
on security later).
https://wcmtl.local/wp-json/wp/v2/users
An Example: Users Endpoint
Let’s Build a Custom Endpoint!
Step-By-Step
1. Custom Post Type
2. Define the route
3. Create the callback function
4. Test your endpoint
5. Build your app and use your endpoint
You can include custom code in your theme or
create a plugin. Whatever you choose, don’t
edit core WordPress files.
You can get a copy of the demo plugin here:
https://github.com/plank/wcmtl-api
1. Create a post type
Since WordPress already has built-in
endpoints for the default post types, most
likely, you’ll need an endpoint for anything
beyond that.
// Add the custom Post type
add_action( 'init', 'wcmtlapi_custom_post_type' );
/**
* Register Custom Post Type
*
* @return void
*/
function wcmtlapi_custom_post_type() {
register_post_type(
'wcmtlapi_cat',
[
'labels' => [
'name' => __( 'Cats', 'wcmtlapi' ),
'singular_name' => __( 'Cat', 'wcmtlapi' ),
],
'public' => false,
'show_ui' => true,
'has_archive' => false,
'hierarchical' => false,
'show_in_rest' => false,
'exclude_from_search' => true,
'capability_type' => 'post',
'rewrite' => [
'slug' => 'cats',
],
'supports' => [
'title',
'editor',
'thumbnail',
],
]
);
}
2. Define a route
Next we’ll need to define the route. The route is
going to be the url that you’ll need to hit to get
your JSON data. It is structured like this:
/wp-json/your-namespace/v1/whatever-
you-want
As of WordPress 5.5, you must provide the
permission_callback parameter. When defining
your endpoints, the permission_callback
parameter defines who has permission to
access the endpoint. Setting this to
__return_true will create a public endpoint
that anyone can access. If the callback used
here returns false, WordPress will return a
rest_forbidden error.
namespace WCMTLAPIpluginAPI;
add_action( 'rest_api_init', __NAMESPACE__ . 'register_routes' );
/**
* Register the routes for the plugin.
*
* @return void
*/
function register_routes() {
$version = '1';
$namespace = 'wcmtl/v' . $version;
// Register Routes
// wp-json/wcmtl/v1/cats
register_rest_route(
$namespace,
'/cats',
[
'methods' => 'GET',
'callback' => __NAMESPACE__ . 'get_cats',
'permission_callback' => '__return_true',
]
);
}
3. Create Callback Function
Create the callback function. This is what builds
and returns the JSON. This is where the magic
happens. You’ll need to always return your data
with the rest_ensure_response() function. This
function will JSON encode the array of data that
you pass it, and make sure that a response code
is sent, ideally 200.
/**
* Callback for the cats endpoint
*
* @return WP_Error|WP_HTTP_Response|WP_REST_Response
*/
function get_cats() {
// WP_Query or logic goes here
$data = [
'cats' => [
[
'name' => 'Pekoe',
'colour' => 'orange',
'breed' => 'domestic shorthair',
'pattern' => 'tabby',
],
[
'name' => 'Milo',
'colour' => 'grey',
'breed' => 'domestic shorthair',
'pattern' => 'solid',
],
[
'name' => 'Poppy',
'colour' => 'cream',
'breed' => 'siamese',
'pattern' => 'pointed',
],
],
];
return rest_ensure_response( $data );
}
4. Test Your Endpoint
Visit your endpoint! Do cool stuff with it, the sky's
the limit. We make React apps to add animation
and interactivity to our frontend builds.
{
cats:
[
{
name: "Pekoe",
colour: "orange",
breed: "domestic shorthair",
pattern: "tabby"
},
{
name: "Milo",
colour: "grey",
breed: "domestic shorthair",
pattern: "solid"
},
{
name: "Poppy",
colour: "cream",
breed: "siamese",
pattern: "pointed"
}
]
}
5. Build your app and use
your endpoint!
Real world example:
Carolina Performing Arts: Southern Futures
The filterable education resources on this page
use two custom API endpoints to power the React
app (Resources + Filters). The result is a lightning
fast filtering system without needing to refresh
the page.
Security
Security
For your first endpoints, create a public GET
endpoint. You won’t need to worry about security, as
the information provided by your custom endpoint
should not be sensitive and will be read-only.
You can create POST, PUT and DELETE endpoints,
but be sure to secure them. You wouldn’t want
someone or an outside system accessing these
endpoints and modifying your database.
There is a way to lock down your endpoints so that
you can only access them if you are logged in as an
administrator or have specific permissions (Or
whatever condition is specified in the
permissions_callback for that particular
endpoint).
Lock It Down
If a user needs to be authenticated to interact with an endpoint, they
must generate an application password and pass along the credentials.
Application Passwords were added in WordPress 5.6 and allow for a
way to authenticate without exposing the user’s primary password. They
can be revoked and regenerated at any time. They are not dissimilar to
an API Key.
curl --user "USERNAME:PASSWORD"
https://HOSTNAME/wp-json/wp/v2/users?context=edit
There are two ways to authenticate natively in WordPress:
1. Cookies (nonces)
2. Application Passwords
Authentication plugins can add other forms of authentication, like OAuth
& JSON web tokens, should you require them.
Q & A
Thank You! Feel Free To Keep in Touch!
https://dev.to/cgarofalo https://profiles.wordpress.org/cold-iron-chef/ https://www.linkedin.com/in/cgarofalo

More Related Content

Similar to Old WP REST API, New Tricks

WebAppSec Updates from W3C
WebAppSec Updates from W3CWebAppSec Updates from W3C
WebAppSec Updates from W3CNatasha Rooney
 
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)James Titcumb
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Mario Cardinal
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
WORDPRESS_REST_API_WORDPRESS_REST_API.pdf
WORDPRESS_REST_API_WORDPRESS_REST_API.pdfWORDPRESS_REST_API_WORDPRESS_REST_API.pdf
WORDPRESS_REST_API_WORDPRESS_REST_API.pdfAngy668409
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsJim Jeffers
 
Great APIs - Future of Your Progress App
Great APIs - Future of Your Progress AppGreat APIs - Future of Your Progress App
Great APIs - Future of Your Progress AppGabriel Lucaciu
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin developmentMostafa Soufi
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5Darren Craig
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress pluginAnthony Montalbano
 
API Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIsAPI Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIsTom Johnson
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationRutul Shah
 
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODEMSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODEannalakshmi35
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)James Titcumb
 
JOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJordan Open Source Association
 
WordCamp Wilmington 2017 WP-API Why?
WordCamp Wilmington 2017   WP-API Why?WordCamp Wilmington 2017   WP-API Why?
WordCamp Wilmington 2017 WP-API Why?Evan Mullins
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB
 

Similar to Old WP REST API, New Tricks (20)

WebAppSec Updates from W3C
WebAppSec Updates from W3CWebAppSec Updates from W3C
WebAppSec Updates from W3C
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
 
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Node.js and Parse
Node.js and ParseNode.js and Parse
Node.js and Parse
 
WORDPRESS_REST_API_WORDPRESS_REST_API.pdf
WORDPRESS_REST_API_WORDPRESS_REST_API.pdfWORDPRESS_REST_API_WORDPRESS_REST_API.pdf
WORDPRESS_REST_API_WORDPRESS_REST_API.pdf
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Great APIs - Future of Your Progress App
Great APIs - Future of Your Progress AppGreat APIs - Future of Your Progress App
Great APIs - Future of Your Progress App
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress plugin
 
API Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIsAPI Workshop: Deep dive into REST APIs
API Workshop: Deep dive into REST APIs
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integration
 
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODEMSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
Kicking off with Zend Expressive and Doctrine ORM (Sunshine PHP 2017)
 
JOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best Practices
 
WordCamp Wilmington 2017 WP-API Why?
WordCamp Wilmington 2017   WP-API Why?WordCamp Wilmington 2017   WP-API Why?
WordCamp Wilmington 2017 WP-API Why?
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless World
 

Recently uploaded

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Recently uploaded (20)

INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Old WP REST API, New Tricks

  • 1. Christina Garofalo @ WordCamp Montréal 2023 | Nov 8, 2023 Old WP REST API, New Tricks How to create a custom REST API endpoint and make cool stuff
  • 2. I’ve always had a knack for figuring things out. I have no formal training in computer sciences, but lots of hands on experience. I’m self-taught I’ve been with the agency for 6 years, and I work with a great collaborative team. I’ve worked with WordPress for about 10 years I joined in person at WCEU Athens 2023. Anyone can contribute. No programming knowledge required! I’m on the WordPress Documentation Team This is my first talk at a WordCamp I’ll happily chat and answer any questions you may have. Bonjour/Hi! Christina Garofalo Senior WordPress Developer
  • 3. Today’s Agenda 1 Introduction 2 What is a REST API? 3 Out-of-the-Box API Endpoints 4 Let’s Build a Custom Endpoint! 5 Security 6 Q & A
  • 5. The WordPress REST API ➔ WordPress introduced the REST API in version 4.7 (2016) and it became the foundation for the WordPress block editor. ➔ The REST API sends and receives data in JSON format, making it easy to integrate into web applications. ➔ With the REST API, it is possible to do things such as build an entirely new admin experience, a completely new interactive front end experience, or create entirely new applications with your WordPress content. ➔ The REST API is one of many WordPress APIs. They are listed here: https://codex.wordpress.org/WordPress_APIs
  • 6. What is a REST API?
  • 7. What can it do? REST APIs have these methods PUT GET POST DELETE Application Programing Interface REpresentational State Transfer A software architecture that imposes conditions of how an API should work. A standardized structure. Additional information HTTP Headers Parameters Data
  • 9. WordPress API Endpoints All WordPress installations have standard endpoints baked in that can be used to manipulate: There is extensive documentation available about the endpoints and all of the parameters found in the REST API handbook. https://developer.wordpress.org/rest-api/ ➔ Posts ➔ Media ➔ Users ➔ Tags ➔ Pages ➔ Comments ➔ Taxonomies ➔ Post Types ➔ Post Statuses ➔ General Blog Settings
  • 10. APIs are not intended for humans to ‘read’. APIs make it possible for systems to talk to each other. Use Firefox or Chrome with the JSONvue extension to see structured JSON in your browser. Otherwise, it’s just a wall of text. Other tools can be used to test endpoints, such as Postman or Insomnia. These apps are more useful for testing endpoints with authentication, POST, PUT and DELETE methods. No Humans Allowed!
  • 11. The most basic WordPress REST API endpoint is simply /wp-json. This will return basic information about the WordPress installation. https://wcmtl.local/wp-json/ { name: "WordCamp Montreal API Demo", description: "A site demonstrating the REST API", url: "http://wcmtl.local", home: "http://wcmtl.local", gmt_offset: -4, timezone_string: "America/Toronto", namespaces: [ "oembed/1.0", "wcmtl/v1", "wp/v2", "wp-site-health/v1", "wp-block-editor/v1" ], authentication: { application-passwords: { endpoints: { authorization: "http://wcmtl.local/wp-admin/ authorize-application.php" } } }, Basic Endpoint
  • 12. [ { id: 1, date: "2023-10-24T18:00:33", date_gmt: "2023-10-24T18:00:33", guid: { rendered: "http://wcmtl.local/?p=1" }, modified: "2023-10-24T18:00:33", modified_gmt: "2023-10-24T18:00:33", slug: "hello-world", status: "publish", type: "post", link: "http://wcmtl.local/hello-world/", title: { rendered: "Hello world!" }, content: { rendered: " <p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p> ", protected: false }, excerpt: { rendered: "<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p> ", protected: false /wp-json/wp/v2/posts This endpoint will return a list of all posts. It can also take parameters (aka arguments): /wp-json/wp/v2/posts?sticky=true https://wcmtl.local/wp-json/wp/v2/posts https://wcmtl.local/wp-json/wp/v2/posts?sticky=true An Example: Posts Endpoint
  • 13. [ { id: 1, name: "Christina", url: "http://wcmtl.local", description: "", link: "https://wcmtl.local/author/christina/", slug: "christina", avatar_urls: { 24: "https://secure.gravatar.com/avatar/575 63c471581211b8818c051015343c5?s=24&d=mm &r=g", 48: "https://secure.gravatar.com/avatar/575 63c471581211b8818c051015343c5?s=48&d=mm &r=g", 96: "https://secure.gravatar.com/avatar/575 63c471581211b8818c051015343c5?s=96&d=mm &r=g" }, /wp-json/wp/v2/users The users endpoint, which is a public endpoint, will return a list of all users subscribed to your site, regardless of role. It does not return the roles associated with the users, but it does return usernames and IDs, which can be used to figure out which account might be an admin and could be an attack vector for the ne’er-do-wells out there looking to gain access to your site. (More on security later). https://wcmtl.local/wp-json/wp/v2/users An Example: Users Endpoint
  • 14. Let’s Build a Custom Endpoint!
  • 15. Step-By-Step 1. Custom Post Type 2. Define the route 3. Create the callback function 4. Test your endpoint 5. Build your app and use your endpoint You can include custom code in your theme or create a plugin. Whatever you choose, don’t edit core WordPress files. You can get a copy of the demo plugin here: https://github.com/plank/wcmtl-api
  • 16. 1. Create a post type Since WordPress already has built-in endpoints for the default post types, most likely, you’ll need an endpoint for anything beyond that. // Add the custom Post type add_action( 'init', 'wcmtlapi_custom_post_type' ); /** * Register Custom Post Type * * @return void */ function wcmtlapi_custom_post_type() { register_post_type( 'wcmtlapi_cat', [ 'labels' => [ 'name' => __( 'Cats', 'wcmtlapi' ), 'singular_name' => __( 'Cat', 'wcmtlapi' ), ], 'public' => false, 'show_ui' => true, 'has_archive' => false, 'hierarchical' => false, 'show_in_rest' => false, 'exclude_from_search' => true, 'capability_type' => 'post', 'rewrite' => [ 'slug' => 'cats', ], 'supports' => [ 'title', 'editor', 'thumbnail', ], ] ); }
  • 17. 2. Define a route Next we’ll need to define the route. The route is going to be the url that you’ll need to hit to get your JSON data. It is structured like this: /wp-json/your-namespace/v1/whatever- you-want As of WordPress 5.5, you must provide the permission_callback parameter. When defining your endpoints, the permission_callback parameter defines who has permission to access the endpoint. Setting this to __return_true will create a public endpoint that anyone can access. If the callback used here returns false, WordPress will return a rest_forbidden error. namespace WCMTLAPIpluginAPI; add_action( 'rest_api_init', __NAMESPACE__ . 'register_routes' ); /** * Register the routes for the plugin. * * @return void */ function register_routes() { $version = '1'; $namespace = 'wcmtl/v' . $version; // Register Routes // wp-json/wcmtl/v1/cats register_rest_route( $namespace, '/cats', [ 'methods' => 'GET', 'callback' => __NAMESPACE__ . 'get_cats', 'permission_callback' => '__return_true', ] ); }
  • 18. 3. Create Callback Function Create the callback function. This is what builds and returns the JSON. This is where the magic happens. You’ll need to always return your data with the rest_ensure_response() function. This function will JSON encode the array of data that you pass it, and make sure that a response code is sent, ideally 200. /** * Callback for the cats endpoint * * @return WP_Error|WP_HTTP_Response|WP_REST_Response */ function get_cats() { // WP_Query or logic goes here $data = [ 'cats' => [ [ 'name' => 'Pekoe', 'colour' => 'orange', 'breed' => 'domestic shorthair', 'pattern' => 'tabby', ], [ 'name' => 'Milo', 'colour' => 'grey', 'breed' => 'domestic shorthair', 'pattern' => 'solid', ], [ 'name' => 'Poppy', 'colour' => 'cream', 'breed' => 'siamese', 'pattern' => 'pointed', ], ], ]; return rest_ensure_response( $data ); }
  • 19. 4. Test Your Endpoint Visit your endpoint! Do cool stuff with it, the sky's the limit. We make React apps to add animation and interactivity to our frontend builds. { cats: [ { name: "Pekoe", colour: "orange", breed: "domestic shorthair", pattern: "tabby" }, { name: "Milo", colour: "grey", breed: "domestic shorthair", pattern: "solid" }, { name: "Poppy", colour: "cream", breed: "siamese", pattern: "pointed" } ] }
  • 20. 5. Build your app and use your endpoint! Real world example: Carolina Performing Arts: Southern Futures The filterable education resources on this page use two custom API endpoints to power the React app (Resources + Filters). The result is a lightning fast filtering system without needing to refresh the page.
  • 22. Security For your first endpoints, create a public GET endpoint. You won’t need to worry about security, as the information provided by your custom endpoint should not be sensitive and will be read-only. You can create POST, PUT and DELETE endpoints, but be sure to secure them. You wouldn’t want someone or an outside system accessing these endpoints and modifying your database. There is a way to lock down your endpoints so that you can only access them if you are logged in as an administrator or have specific permissions (Or whatever condition is specified in the permissions_callback for that particular endpoint). Lock It Down If a user needs to be authenticated to interact with an endpoint, they must generate an application password and pass along the credentials. Application Passwords were added in WordPress 5.6 and allow for a way to authenticate without exposing the user’s primary password. They can be revoked and regenerated at any time. They are not dissimilar to an API Key. curl --user "USERNAME:PASSWORD" https://HOSTNAME/wp-json/wp/v2/users?context=edit There are two ways to authenticate natively in WordPress: 1. Cookies (nonces) 2. Application Passwords Authentication plugins can add other forms of authentication, like OAuth & JSON web tokens, should you require them.
  • 23. Q & A
  • 24. Thank You! Feel Free To Keep in Touch! https://dev.to/cgarofalo https://profiles.wordpress.org/cold-iron-chef/ https://www.linkedin.com/in/cgarofalo