Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Learning WordPress REST API
Learning WordPress REST API
Learning WordPress REST API
Ebook446 pages3 hours

Learning WordPress REST API

Rating: 0 out of 5 stars

()

Read preview

About this ebook

About This Book
  • Learn how to run the latest WordPress REST API with various platforms
  • Create exciting apps and manage non-WordPress content with them
  • Secure, export, and manage your data through illustrative examples
Who This Book Is For

This book is for WordPress developers and designers who want to get a complete practical understanding of the WordPress REST API and leverage it to create fully-featured web apps.

LanguageEnglish
Release dateJul 28, 2016
ISBN9781786460233
Learning WordPress REST API

Related to Learning WordPress REST API

Related ebooks

Programming For You

View More

Related articles

Reviews for Learning WordPress REST API

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Learning WordPress REST API - Sufyan bin Uzayr

    Table of Contents

    Learning WordPress REST API

    Credits

    About the Authors

    Acknowledgments

    About the Reviewer

    www.PacktPub.com

    Why subscribe?

    Free access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Getting Started with REST API

    Introducing REST API

    Defining API

    Defining REST

    Defining JSON

    Using REST API in real-world applications

    Advantages of REST services

    Key considerations when working with REST

    Architectural components in REST

    Design principles in REST

    Getting started with REST implementation

    Passing commands in SOAP versus REST

    Handling data in REST

    Using REST in different programming languages

    Ruby

    Python

    Perl

    C#

    Java

    PHP

    JavaScript

    REST API in WordPress

    Universality

    Remote management

    Third-party support

    Summary

    2. Interacting with REST API in WordPress

    Getting started

    Issuing requests via Postman

    HTTP API in WordPress

    Fetching GET post output in JSON objects

    Issuing queries

    Interacting REST API via PHP

    Explanation of function

    Issuing POST requests

    Implementing GET meta fields using REST API in WordPress

    Implementing POST meta fields using REST API in WordPress

    Summary

    3. Working with Taxonomies and Users with REST API

    Working with taxonomies in WordPress using REST API

    Basics

    HTTP requests

    Implementing REST API and JavaScript with taxonomies

    How to send GET requests for taxonomies

    How to send POST requests for taxonomies

    Working with users in WordPress using REST API

    How to GET user data using REST API in WordPress

    GET public user data

    GET privileged user data

    How to POST (and edit) user data using REST API in WordPress

    Summary

    4. Working with Forms Using REST API

    Overview

    Fundamentals

    Setting up the plugin

    Creating the form with HTML markup

    Enqueueing your JavaScript file

    Issuing requests for creating posts

    OAuth authorization method

    Issuing requests for editing posts

    Summary

    5. Custom Routes in WordPress REST API

    Overview

    Adding custom routes to WordPress REST API

    Setting up the custom route

    Route namespace

    URL after namespace

    Endpoints to a route

    Optional Boolean argument

    Setting up the custom endpoints

    Transport method

    Defining our fields

    The callback function

    The permissions callback

    Processing requests (and responses)

    WP_Query

    WPDB

    get_post_meta

    Third-party plugins

    Summary

    6. Creating a Simple Web App using WordPress REST API

    Overview

    Setting up your WordPress site

    Cross origin problems and bugs

    Handling multiple requests

    Optimization measures

    Steps to disable the default routes

    More about WP REST API

    The REST architecture

    HTTP verbs

    Endpoints and routes

    JSON REST API for WordPress

    JSON REST APIs in WordPress

    WP REST API at the moment

    Tools

    Installing the plugin

    Going further

    WP REST API – setting up and using basic authentication

    Authentication

    WP REST API authentication

    Basic authentication

    Installing the plugin

    Postman requests

    Authenticated requests from the command line

    JavaScript authenticated requests

    WP HTTP API for authenticated requests

    Status check

    WP REST API - setting up and using advanced authentication

    OAuth authentication

    OAuth security concerns

    OAuth 2.0

    OAuth authentication flow

    Oauth_callback function

    OAuth_verifier function

    OAuth installation

    Assessing the availability of the OAuth API

    Application management

    Generating OAuth credentials

    User authorization

    Token exchange

    Status check

    WP REST API - retrieving data

    The GET request

    Options request

    Retrieving posts from the server

    The filter[] syntax

    Post revisions, categories, tags, and meta

    Other resources

    Status check

    WP REST API: creating and editing posts

    CRUD methods in routes

    Creating and updating posts

    Creating and updating post meta

    Creating and updating data

    Sending data as URL parameters

    Sending data as a JSON object

    Sending data using forms

    Uploading media via multipart/form-data

    Deleting data

    Status check

    WP REST API: internals and customization

    Internal classes and methods of WP REST API

    Infrastructure classes

    WP_REST_Server

    WP_REST_Request

    WP_REST_Response

    Modifying server responses

    The register_rest_field()

    Summary

    7. Mastering REST API for Your Projects

    Backward compatibility

    A universal API

    Architectural structure

    REST architectural constraints

    The formal REST constraints

    Stateless

    Client-server

    Layered system

    Cacheable

    Code on demand

    Uniform interfaces

    Resource identification

    Representation and resources

    Self-descriptive messages

    HATEOS

    Ever-growing REST API

    REST API as a platform

    Implementing REST API in apps

    Custom data types in WordPress

    REST API in later versions of WordPress

    REST API and WordPress plugin development

    REST API-based authentication

    OAuth authentication

    Basic authentication

    Cookie authentication

    REST API and security

    REST API being used in WordPress plugins

    Overview

    Disabling REST API

    Summary

    8. WordPress REST API in Practice

    Key differences between v1 and v2 of the plugin

    Internal changes

    External changes

    Future changes

    Functions of APIs

    The REST API in theory

    A guide to HTTP and REST

    HTTP

    HTTP client libraries

    The WordPress REST API

    The JSON REST API

    Developers of WP REST API

    Overall description

    JSON

    JavaScript

    WP REST API and JavaScript

    XML-RPC in WordPress

    REST API revenue sources

    Mobile applications

    Wearable devices

    SaaS services

    Third-party apps

    Web services

    Competing architectures on the Web

    RESTful architectures

    RPC architectures

    Combination of REST and RPC

    Overview of architectures

    JavaScript and WordPress

    AJAX in WordPress

    Things to consider when using REST API

    Interacting with databases using REST API

    Doing more with REST API

    Current status of REST API

    WordPress features

    REST API conclusion

    Progressive enhancement of WP REST API

    WordPress Calypso and the REST API

    Securing a REST API

    OAuth protocol

    WordPress API and regular users

    Building your own API

    Drawbacks of a custom API

    REST API management

    Implementation of custom services for REST API

    Integration of REST API with mobile applications

    Standards for custom REST APIs

    Custom API tokens

    Summary

    9. Summing It Up

    Comparison of REST API with XML-RPC

    RPC versus REST

    Keypoints

    Disadvantages of XML-RPC

    XML-RPC usage in WordPress

    Usage of XML RPC

    REST API token-based authentication

    Making sure your apps and sites are backward-compatible

    Backward compatibility in practice

    New functionality

    Preventing script breaking

    The future of REST API

    What will happen with REST in the future?

    PHP and WordPress

    Mobile integration

    The backend

    REST API plugin versions

    Goals for REST API

    Limitations of REST API

    Summary

    Learning WordPress REST API


    Learning WordPress REST API

    Copyright © 2016 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: July 2016

    Production reference: 1180716

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham 

    B3 2PB, UK.

    ISBN 978-1-78646-924-3

    www.packtpub.com

    Credits

    About the Authors

    Sufyan bin Uzayr is a writer and web developer with experience and an interest in a lot of things related to web design and development. He has worked with numerous Content Management Systems and frameworks, and writes about web design, web development, content production, branding, and typography for several blogs and magazines of repute. He also has a background in Linux administration, database management, cloud computing, and web hosting.

    Sufyan is an open source enthusiast. He can code in PHP, RoR, and Perl, and is also proficient in JavaScript, jQuery, and HTML5/CSS3, as well as several other web development trends.

    Sufyan primarily uses WordPress and Drupal for both personal and client projects, and often turns towards MODX for the deployment of cloud sites. He has been working with Drupal, WordPress, and other CMSs for almost a decade by now.

    Sufyan is a prolific author, and has written several books on a diverse range of topics, including concrete5 for developers (published by Packt Publishing in 2014). He is associated with various publications in the field of web design and development, both in writing and editorial capacity. He has also served as the News Editor and Technical Supervisor, as well as Editor-in-Chief, for multiple web development magazines, both online and in print.

    Apart from technology and coding, Sufyan also takes a keen interest in topics such as History, Current Affairs, Foreign Policy and Politics, and regularly appears on television and radio shows around the world. He is also a featured columnist for multiple journals and news publications focusing on foreign policy and international relations. Sufyan's writings on contemporary issues are simultaneously translated into different languages, and his works are cited in academic and critical journals on a regular basis.

    Sufyan manages https://codecarbon.com, which features an assortment of useful tools and resources for web developers. Updated regularly, Code Carbon offers JavaScript frameworks and libraries, as well as resources related to HTML/CSS, PHP, Python, Ruby, and of course, WordPress.

    You can learn more about Sufyan's writings and other non-technical works at the following website: http://sufyanism.com.

    Mathew Rooney is a coder with multiple years of experience in the web development industry. He works with PHP, JavaScript, and offers custom-coded WordPress themes and plugins. Mathew is a firm believer in open source software and has been using WordPress for nearly 5 years.

    Acknowledgments

    There are several people who deserve to be this page, because this book would not have come into existence without their support.

    Some names deserve a special mention, and I am genuinely indebted to:

    Mathew Rooney, for the help he offered by co-authoring sections of this book. A good part of the code in different segments and chapters of this book was handled by him. Reshma Raman, for ensuring that the book stays on track, and the outline and chapter division is in the best possible shape.

    Prashanth G, for editing the book, and making sure that the content is in order, and also for formatting the manuscript to make it adhere to the Packt style guide.

    Shivani Mistry, for the technical edits, and for taking care of the book during the production stage.

    Joe Perkins, and all the great folks at Tap Managed WordPress hosting, for offering me a free WordPress setup with no restrictions, wherein I could implement and debug the code.

    Stelian Subotin, for helping me remain calm by keeping track of the theoretical aspects of the book.

    Ahmad Awais, for reviewing the manuscript, and for providing his helpful insight and critical assessment.

    And of course, the core contributors of WordPress, the team behind WP REST API, as well as the millions within the WordPress community -- this book would not have existed had WordPress not been there, and WordPress itself would not be so popular if it were not for the amazing community.

    -- Sufyan bin Uzayr

    About the Reviewer

    Ahmad Awais is a senior full stack web and business development strategist with substantial industrial experience in development, design, training, and writing everything about WordPress.

    He blogs at https://AhmadAwais.com/ and tweets at @MrAhmadAwais. He also contributes to projects such as WP-API, WP Customize Component, WooCommerce, TwentySixteen, Easy Digital Downloads, and the WordPress, PHP, and JS Communities.

    Ahmad is also one of the keenest open source evangelists; a core contributor at WordPress; a maker of lots of FOSS (Free and Open Source Software), especially WPGulp Boilerplate being used by more than 100 developers, and Sublime Text WordPressCustomizer Package, helping about 1,000 developers write quality code with ease.

    He is a published author and WordPress Content Lead at sites such as WPLift, Envato Tuts+, Torque Mag by WPEngine, SitePoint, SmashingMagazine, CreativeMarket, HongKiat, SpeckyBoy, wpMail, Post Status, WPBeginner, TheLayout by FlyWheel, ProductHunt Maker, and so on.

    I'd like to thank my parents, Maedah Batool (WP Journalist) for their never-ending support; Packt Publishing, the WordPress Core Team, and the community (developers, designers, and users), without whom none of this would have been possible.

    www.PacktPub.com

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Free access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

    Preface

    The REST API is the next big thing in the world of WordPress development. Ever since its inception, it has been gaining popularity, and more and more developers are turning towards it.

    Of course, the REST API comes with numerous benefits, such as the ability to interact with third-party platforms and apps. Have an application coded in Ruby and want to interact with a WordPress site based on PHP? The REST API is here to help you!

    This book will help you get started with the REST API for WordPress. You will learn the basics as well as the advanced details of this new API so that you can use it in your projects.

    What this book covers

    Chapter 1, Getting Started with REST API, gives you an overview of what the REST API is, how it functions, and all that it is capable of doing. You will also find information about other platforms if you are new to WordPress.

    Chapter 2, Interacting with REST API in WordPress, is where you will learn the basics of the REST API in WordPress. General POST and GET commands shall be covered here.

    Chapter 3, Working with Taxonomies and Users with REST API, moves to taxonomies such as categories and tags. Users and user roles will also be covered.

    Chapter 4, Working with Forms Using REST API, will show you how the REST API can be used to work with custom forms for your WP platform. This chapter will teach you how to get the most out of it.

    Chapter 5, Custom Routes in WordPress REST API, progresses beyond default roles and teaches you how to add and work with custom routes using the REST API.

    Chapter 6, Creating a Simple Web App Using WordPress REST API, is where you learn how to create a web app. Plus, you will also learn how to pass commands to your web app.

    Chapter 7, Mastering REST API for Your Projects, is where you will learn how to master the REST API for your projects. Obviously, this chapter requires that you have a working knowledge of the REST API, as well as experience with WordPress development.

    Chapter 8, WordPress REST API in Practice, teaches you the practical aspects of the WP REST API and its development.

    Chapter 9, Summing It Up, wraps up our journey with the WordPress REST API. We will have a recap of all that we have learned so far and an overview of what the REST API can do for us.

    What you need for this book

    Obviously, you will need a working installation of WordPress to begin with. The latest version of WordPress is recommended so that you do not miss out on security updates.

    You will also need to install and activate the WordPress REST API plugin on your site. Free download and installation instructions are here: https://wordpress.org/plugins/rest-api/.

    At least PHP 5.4 or higher is recommended. The latest supported version of MySQL is required as well, and enhancements such as MariaDB are also allowed.

    You can run WP on a generic LAMP or WAMP stack. For further instructions, consider reading the WordPress documentation.

    Who this book is for

    This book is for WordPress developers and designers who want to get a complete practical understanding of the WordPress REST API and leverage it to create fully featured web apps.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: HTTP requests in JavaScript require the XMLHttpRequest object.

    A block of code is set as follows:

    require 'net/http'

    url = 'http://www.example.com/database/1191'

    resp = Net::HTTP.get_response(URI.parse(url))

    resp_text = resp.body

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    require 'net/http' url = 'http://www.example.com/database/1191'

     

    resp = Net::HTTP.get_response(URI.parse(url))

    resp_text = resp.body

    Any command-line input or output is written as follows:

    $url = http://www.example.com/database/1191; $response = file_get_contents($url); echo $response;

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Hit Preview link in the pane and you will see your remote WordPress site in the panel.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail

    Enjoying the preview?
    Page 1 of 1