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

NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationNeilDeclaro1
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactisticshameyhk98
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 

Recently uploaded (20)

NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 

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