REST API: Introduce dashboard namespace

Summary

We propose to introduce a dashboard REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. namespace prefix, for use on endpoints specifically relating to the WordPress adminadmin (and super admin) dashboard.

Motivation

WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. currently contains two namespace prefixes: wp and oembed. These represent two separate APIs offered by WordPress: the general REST API which exposes structured WordPress data objects to external clients, and the OEmbed implementation.

The general design of WordPress distinguishes between the core, and the Dashboard “application” built on top of it. These two have not traditionally been formally separated, however the design and clean slate of the REST API allows us to consider these separately as we evolve the Dashboard.

With the push towards removing admin-ajax handlers in favour of new REST API endpoints, there are naturally APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. endpoints being introduced which are not useful outside of the administrative interface. Endpoints for Dashboard Widgets, pointers, and other features are specific to the Dashboard application, and are not broadly applicable to public-facing WordPress sites or third-party applications.

Introducing a new dashboard namespace prefix allows separating Dashboard-specific endpoints from the public WordPress REST API. This can also allow for future changes, deprecations, and new versions of the Dashboard API without requiring a version bump for the public REST API.

Detailed design

New endpoints for the Dashboard will live under dashboard/, initially with the namespace dashboard/v1 for the first version of endpoints.

Future iterations of the Dashboard that need to break API backwards compatibility can increment the version under the same namespace prefix as needed (e.g. dashboard/v2dashboard/v3). These new versions do not need to affect the public WordPress REST API.

This requires no code changes, as it simply designates the namespace for future use. The first endpoints to be added under this new namespace are expected to be the endpoints for Site Health (#48105) in WordPress 5.4.

How do we communicate this?

The new endpoints under the dashboard namespace prefix will collectively be called the Dashboard REST API to distinguish them from the public WordPress REST API.

There are no user-facing changes resulting from this proposal. Likewise, there is no effect on pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party, theme, or API client developers.

The difference between wp and dashboard needs to be communicated to core developers working on the Dashboard and related features. The announcement of this RFC on the Make/Core blogblog (versus network, site) will serve as an initial announcement, but evergreen documentation should be added to the Core Handbook.

A new page will be added to the REST API Handbook under the “Best Practices” section, outlining design guidelines for new endpoints added to WordPress Core. The proposed text for this page is:

REST API

Core implementations of REST API endpoints should follow some simple rules to ensure WordPress provides a consistent public data interface.

Creating New Endpoints

Where possible, core features should use existing REST API endpoints rather than adding new ones. For example, a tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) search feature should use the existing tag collection endpoint in the REST API rather than building one specifically for the feature.

When a new endpoint is required, care should be put into the design of the external API. In particular, the shape and schema of the resource, the namespace, the route (URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org), and the available actions should match existing precedent in core.

REST API endpoints intended for public use and which represent “core” features of WordPress should be under the public REST API namespace (wp/v2). Endpoints which are only applicable for the Dashboard (e.g. Dashboard Widgets, pointers, or other UIUI User interface settings) should be under the Dashboard REST API namespace (dashboard/v1). This ensures a clear distinction between APIs for general consumption and APIs built for specific UI features.

The design and implementation of the endpoint can be checked by the REST API team before committing to ensure it is consistent with the rest of the API. This helps us provide a more consistent experience for API consumers.

Drawbacks

Introducing a new core namespace could impact third-party plugins or other code which uses the same namespace string. This represents a minor backwards compatibility break, and investigation needs to be done as to whether we’re breaking any major plugins with this change.

It could also be argued that it fragments core’s API surface to introduce an entirely new namespace. Making the distinction of which namespace to use is tough, and this might lead to features that could have general applicability existing only as part of the Dashboard API, without a public API for use by external clients.

In addition, adding a new namespace opens the question of whether more even namespaces are needed. For example, should there be a CustomizerCustomizer Tool built into WordPress core that hooks into most modern themes. You can use it to preview and modify many of your site’s appearance settings. namespace? Do other features need their own namespaces as well?

Alternatives

There are a few main alternatives to creating a dashboard namespace prefix.

The first is to use the current wp/v2 namespace for endpoints relating to administrative interfaces like Site Health. The main reason to avoid doing this is that it couples Dashboard-specific features to the public REST API. These features are rarely applicable or usable outside of the Dashboard application, especially in third-party plugin interfaces or external clients. In addition, this would also tie Dashboard API versioning to the public REST API, which could lead to the public REST API version being needlessly bumped for Dashboard-only changes.

Another alternative is to use a sub-namespace prefix of the existing wp prefix, such as wp/dashboard. This avoids any risk of impacting existing plugins as wp is already known to be reserved for core. However, this breaks the current precedent of <prefix>/v<version>, increasing the complexity of API namespacing. Given that it is unlikely that the dashboard prefix is currently being used, the simpler option of dashboard/v1 is preferred. This also discourages a proliferation of sub-namespaces under the wp prefix.

The final alternative is creating a separate namespace for each feature, such as site-health/v1. This could have the advantage of making endpoints more discoverable, and would reduce the overall length of each endpoint’s URIs. A dashboard prefix may also imply that its endpoints are “private” to WordPress and specific to the WordPress display context in cases where future endpoints may be useful in third-party tools. This approach has the disadvantage that plugin developers may worry that any namespace they pick could eventually be reappropriated by WordPress core.

Unresolved Questions

  • Should we use admin/v1 or dashboard/v1? To some dashboard is unclear and meaningless, to others admin is very specific to wp-admin whereas dashboard is more general idea of management.
  • Should we use dashboard/v1 or wp/dashboard/v1? The former could potentially clash with plugins, and is much more generic. We also need to pave the way for further namespaces that may be added to core in the future, where clashes may be more common.

Originally written by @rmccue as a WP-API Proposal.

#5-4, #rest-api, #site-health

REST API Chat Summary: November 14

This post summarizes the weekly REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. chat meeting for November 7, 2019. (Slack transcriptAgenda). Weekly REST API component office hours are held every Thursday at 18:00 UTC in the #core-restapi room in the Make WordPress SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/..

Authentication

A new wp-api/authentication GitHub repository was created last week to facilitate the design & development of a REST API authentication solution for WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress..

We continue to be in the information gathering stage. For all interested in contributing to this effort, we will be using part of our weekly REST API office hours each Thursday at 18:00 UTC (Thursday, November 14, 2019, 01:00 PM EST) as a weekly standup to coordinate work.

We also invite you to log issues describing use cases the authentication solution should support.

Registered BlockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. Types REST API

#47620 aims to create REST API routes to discover the list of registered block types. It is based off the Gutenberg Block Type Registration RFC. @spacedmonkey worked on a patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing. and is in the process of soliciting feedback from the GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ team, Mobile team, and other members of the REST API team.

A particular point of concern @spacedmonkey brought up was the difficulties about handling the asset fields ( editorScript, script, editorStyle and style ). The RFC defines the fields as either absolute URLs or relative paths to the source files. However the WP_Block_Type class defines those fields as asset handles.

Further the asset URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org or handle is not sufficient to make the asset functional. The list of dependencies, inline scripts, translations, and localized data are all necessary for the script to work.

@timothyblynjacobs mentioned that the RFC discusses statically discovering that information from an associated .asset.json file located “next” to the script file. @aduth mentioned that section is slightly out of date since @wordpress/scripts now outputs a .php file instead of a JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. file.

The participants discussed whether it would be better to include this additional information inline in the Block Type response, or to develop a separate wp/v2/dependencies APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways..

@timothyblynjacobs suggested that including this information inline would be simpler. @spacedmonkey pointed out that then we’d be including full data from a separate resource within the block type response. Elsewhere in the REST API that would be handled by creating a separate API and linking to it.

Additionally, @timothyblynjacobs pointed out that just exposing the list of dependencies isn’t sufficient. The client needs access to the entire dependency graph to ensure each dependency’s dependencies are loaded, and that all scripts are loaded in the correct order.

This all points to a dedicated REST API endpoint being a better solution. The team then discussed the potential privacy and security ramifications about retrieving this information about any registered asset.

A developer may include sensitive data in a wp_localize_script or wp_add_inline_script after registering the script with wp_register_script. Currently, this data would only be exposed when the script is enqueued, which may be protected by a current_user_can or $hook-suffix check. If the REST API allowed returning information about an arbitrary asset handle, this data may be exposed.

Additionally, a developer may conditionally registers asset based on a pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party’s settings. By allowing a user to check if a handle is registered via the REST API, it may be possible to determine the setting configuration of a plugin. This may not be desirable for security or privacy related plugins.

@kadamwhite mentioned that historically the REST API has been pretty conservative about what data is exposed. If possible, he’d like to continue along that path. Or theoretically authentication could be required for some pieces of the API since the use case seems to mostly be for editorial interfaces which would require auth anyway. @spacedmonkey also suggested a capability check.

@spacedmonkey and @timothyblynjacobs proposed limiting the assets exposed to ones registered via WP_Block_Type and all WordPress Core assets. Additional assets could be exposed via a registration flag of some kind, like show_in_rest.

Both @aduth and @youknowriad mentioned that this functionality would not just be useful for blocks. As WordPress moves more and more to JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors. powered interfaces, the ability to lazy load assets will become increasingly important. The problem here could be generalized to “retrieve all the information necessary to properly load a handle”.

@youknowriad opened a ticketticket Created for both bug reports and feature development on the bug tracker., #48654, to continue the discussion on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress..

Agenda for November 21

The next REST API meeting is happening in #core-restapi at Thursday, November 21 at 18:00 UTC. Agenda:

  • REST API Authentication project weekly meeting
  • Menus API discussion
  • WP Dependencies API
  • Review open tickets which should be provisionally milestoned for 5.4
  • Open floor

#meeting-notes, #rest-api

REST API Chat Summary: November 7

This post summarizes the weekly REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. chat meeting for November 7, 2019. (Slack transcript, Agenda). Please note that this meeting did not change time for daylight savings, and Weekly REST API component office hours continue to be held every Thursday at 18:00 UTC in the #core-restapi room in the Make WordPress SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/.. 🙂

Authentication

The first half of the meeting discussed the newly-created wp-api/authentication GitHub repository, a follow-up to discussions at WCUS contributor dayContributor Day Contributor Days are standalone days, frequently held before or after WordCamps but they can also happen at any time. They are events where people get together to work on various areas of https://make.wordpress.org/ There are many teams that people can participate in, each with a different focus. https://2017.us.wordcamp.org/contributor-day/ https://make.wordpress.org/support/handbook/getting-started/getting-started-at-a-contributor-day/. around rebooting work towards a canonical, coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. Authentication solution to permit the Mobile team to use the REST API instead of XMLRPC.

Our target for a merge proposal some time next year is to have an use the OAuth 2 handshake flow with dynamic client registration, which issues revocable, long-lived JWT tokens. The repo has no content so far, but we will start work by focusing on UX and the desired user-facing and technical flow rather than diving immediately into code.

@spacedmonkey, @derekherman, and others intend to drive this project over the coming months. If you who is reading this or any colleagues of yours are interested in contributing to this effort, we will be using part of our weekly REST API office hours each Thursday at 18:00 UTC (Thursday at 18:00 UTC) as a weekly standup to coordinate work.

Priorities & Goals

Priorities for Next Release

Key tickets highlighted for consideration as part of the next release cycle include, but are not limited to,

  • Improve performance in route matching #48530
  • Support registered default metaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress. values #43941
  • Permit schema filtering #47779

If you have a ticketticket Created for both bug reports and feature development on the bug tracker. to highlight or propose for the next bugfix or major releasemajor release A release, identified by the first two numbers (3.6), which is the focus of a full release cycle and feature development. WordPress uses decimaling count for major release versions, so 2.8, 2.9, 3.0, and 3.1 are sequential and comparable in scope., please leave it as a comment below or raise it in #core-restapi. Thank you once more, as well, to everybody who helped drive our API improvements in 5.3!

Documentation

We are behind schedule in updating the REST API handbook to cover the recent changes in WordPress 5.3. @timothyblynjacobs and @kadamwhite will be working to roll these updates out over the coming week. Handbook content is managed at github.com/wp-api/docs.

Open Floor

@timothyblynjacobs raised #44568 and #44886. Because WordPress operations are non-atomic, these race condition issues are not limited to the REST API and were determined to be out-of-scope, so #44886 was closed as wontfixwontfix A resolution on the bug tracker (and generally common in software development) that indicates the ticket will not be addressed further. This may be used for acceptable edge cases (for bugs), or enhancements that have been rejected for core inclusion..

Several bugs were raised and have been provisionally milestoned for 5.4, with the option to backportbackport A port is when code from one branch (or trunk) is merged into another branch or trunk. Some changes in WordPress point releases are the result of backporting code from trunk to the release branch. as needed once addressed.

To increase contributor awareness of REST API tickets, we discussed holding periodic component scrub meetings in the main #core channel.

Agenda for November 14

The next REST API meeting is happening shortly in #core-restapi at Thursday, November 14, 18:00 UTC. Agenda:

  • REST API Authentication project weekly meeting
  • Review open tickets which should be provisionally milestoned for 5.4
  • Open floor

#meeting-notes, #rest-api

REST API Meeting Agenda for Nov 7

The REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. weekly component chat will occur this week at November 7, 2019 18:00 UTC in the #core-restapi SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. channel.

Please note: We have not changed the UTC time for this meeting. If your country has recently adjusted for daylight savings time, this may be a different hour than the past few months.

Agenda Items:

  • Continue discussion from WordCampWordCamp WordCamps are casual, locally-organized conferences covering everything related to WordPress. They're one of the places where the WordPress community comes together to teach one another what they’ve learned throughout the year and share the joy. Learn more. US around a canonical authentication solution and begin tasking out work towards that effort
  • Discuss priorities for the 5.4 development cycle
  • Discuss needed documentation improvements
  • Open Floor

All agenda items are welcome, from all teams and contributors; please post them as comments below or let us know by joining the meeting.

#agenda, #rest-api

The REST API in WordPress 5.3

WordPress 5.3 contains a number of REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. improvements designed to make it easier and faster to work with APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. data from the blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. editor or other client applications.

Register Array & Object Metadata

As covered previously in this developer note on array & object metadata, it is now possible to use register_post_meta & register_term_meta (as well as the underlying method register_meta) to interact with complex metaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress. values as schema-validated JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. arrays or objects using the REST API. See the linked post for more details.

Nested response filtering with _fields query parameter

This developer note on the changes to the REST API’s _fields= query parameter shows how you may now filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. your REST API response objects to include only specific nested properties within the response body.

Ticketticket Created for both bug reports and feature development on the bug tracker. #42094

Set drafts back to “floating date” status

Once a date has been set for a draft, it was previously impossible to set the post back to showing “publish immediately” (also referred to as a “floating date,” where the post will be dated whenever it is published). As of 5.3, passing null for a date value will unset the draft date and restore this floating state.

Ticket #39953

Faster Responses

We have introduced a caching wrapper around the generation of REST resource schema objects, which initial testing has shown to yield up to a 30-40% performance increase in large API responses. If you work with expensive or large REST API queries, things should be quite a bit faster now. (Ticket #47871)

The REST API has also been improved to avoid unnecessary controller object instantiation (#45677) and to skip generation of sample permalinks when that data is not requested (#45605).

Please Note: if your team has existing performance benchmarking tooling for the REST API, please contact the component maintainers in the #core-restapi SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. channel; we very much desire to expand our metrics in this area.

Additional Changes of Note

In addition to these key enhancements, there are a number of smaller improvements to the REST API which may be of interest to developers.

  • It is no longer possible to DELETE a Revision resource using the REST API, as this behavior could break a post’s audit trail. Ticket #43709
  • The /search endpoint will now correctly embed the full original body of each matched resource when passing the _embed query parameter. Ticket #47684
  • rest_do_request and rest_ensure_request now accept a string API path, so it is possible to instantiate a request in PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher using nothing more than the desired endpoint string, e.g.
    rest_do_request( '/wp/v2/posts' );
    Ticket #40614
  • Creating or updating a Terms resource via the REST API now returns the updated object using the “edit” context. Ticket #41411
  • It is now possible to edit a posted comment through the REST API when authenticating the request as a user with the moderate_comments capability. Previously a full editor- or adminadmin (and super admin)-level role was needed. Ticket #47024
  • rest_get_avatar_urls now receives the entire User or Comment object, not just the object’s email address. Ticket #40030

Welcoming Timothy Jacobs as a REST API component maintainer

Last but not least, many of you have no doubt seen @timothyblynjacobs active in tracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress., slack, and community events. Timothy has driven much of the momentum that resulted in the above improvements, and I’m excited to (belatedly) announce that he has joined the REST API team as an official component maintainer. Thank you very much for your energy and dedication!

Thank you also to every other person who contributed to API changes this cycle; it’s the best version of the REST API yet, and we couldn’t have done it without the dozens of contributors who helped create, review and land these patches.

We’ve got some ambitious ideas about how we can make the REST API even better in 5.4. Interested in helping out, with code, docs, or triagetriage The act of evaluating and sorting bug reports, in order to decide priority, severity, and other factors.? Join us for weekly office hours, every week on Thursdays at 1800 UTC!

#5-3, #dev-notes, #rest-api

Filtering nested REST response _fields in WP 5.3

WordPress 4.9.8 introduced the ability to limit the fields included in the JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. objects returned from the REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/., for example specifying

/wp/v2/posts?_fields=id,title,author

to return a list of posts with only id, title & author fields in situations where we don’t need all of the data contained in other fields like content or media (see #38131). Since 4.9.8 we’ve made further improvements to skip computing fields we did not explicitly request when _fields is present, saving time on the server in addition to slimming down the JSON response object.

In WordPress 5.3 we are adding the ability to filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. by nested fields. Previously we could only request top-level properties like content or meta, which would return the full content object (with raw and rendered properties when using an edit context) or the object containing all metaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress. values. We can now specify a nested path such as content.raw and the REST API will skip computing the rendered content, a useful performance boost for applications like GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ which only require that underlying raw post content.

Now that we can register complex array or object meta, we may similarly ask for only a few of many registered meta fields, or certain properties within a complex object, using a query such as this:

?_fields=meta.meta-key-1,meta.meta-key-2,meta.meta-key-3.nested-prop

(Note that this specific meta example depends on bugfix #48266, which will ship as part of RC1.)

Thank you @timothyblynjacobs, @dlh, @danielbachhuber, and @rmccue for assisting with the development of this useful feature!

#5-3, #dev-notes, #rest-api

WP 5.3 Supports Object and Array Meta Types in the REST API

With WordPress 5.3, the register_meta functions (including register_post_meta) now support the 'object' and 'array' data types. Previously, the recommended solution to create complex metaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress.-based GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ blocks was to JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. encode the blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience.’s complex attribute value, and pass that string to the APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways.. The REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. now natively supports those complex metadata types. This allows leveraging the REST API to perform schema-based validation, and should additionally simplify client code which interacts with these complex values through the REST API.

Importantly, these data types follow the JSON specification, not the PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher definition. For comparison, that means a JSON object type is equivalent to an associative array in PHP. The JSON array type is a numerically indexed array.

When registering a complex meta field, it is almost always required to also specify a JSON schema describing the expected structure. This can be done by switching show_in_rest from a simple true value, to an array that specifies the desired schema under the schema array key.

Object Example

The following code sample registers a post meta field called “release” that accepts the given JSON data.

{
  "meta": {
    "release": {
      "version": "5.2",
      "artist": "Jaco"
    }
  }
}
register_post_meta(
     'post',
     'release',
     array(
         'single'       => true,
         'type'         => 'object',
         'show_in_rest' => array(
             'schema' => array(
                 'type'       => 'object',
                 'properties' => array(
                     'version' => array(
                         'type' => 'string',
                     ),
                     'artist'  => array(
                         'type' => 'string',
                     ),
                 ),
             ),
         ),
     )
 );

By default, only properties that are explicitly specified in the schema will be allowed. The additionalProperties keyword can be used to to change this behavior. additionalProperties should be another JSON schema that is used to validate any unknown object members. For instance, to enforce that any additional properties are numbers, the following code can be used.

{
   "meta": {
     "release": {
       "version": "5.2",
       "artist": "Jaco",
       "unknown_field": 5.3
     }
   }
 }
register_post_meta(
     'post',
     'version',
     array(
         'single'       => true,
         'type'         => 'object',
         'show_in_rest' => array(
             'schema' => array(
                 'type'       => 'object',
                 'properties' => array(
                     'version' => array(
                         'type' => 'string',
                     ),
                     'artist'  => array(
                         'type' => 'string',
                     ),
                 ),
                 'additionalProperties' => array(
                     'type' => 'number',
                 ),
             ),
         ),
     )
 );

Additionally, additionalProperties can be set to true to allow unknown properties of any format, but this is not recommended.

Array Example

The following code sample registers a post meta field called “projects” that contains a list of project names that accepts the given JSON data.

{
   "meta": {
     "projects": [
       "WordPress",
       "BuddyPress"
     ]
   }
 }
register_post_meta(
     'post',
     'projects',
     array(
         'single'       => true,
         'type'         => 'array',
         'show_in_rest' => array(
             'schema' => array(
                 'type'  => 'array',
                 'items' => array(
                     'type' => 'string',
                 ),
             ),
         ),
     )
 );

The “items” keyword is used to define the JSON schema to validate each array member against. It can be a simple type like “string” or a complex type like “object”.

For instance, to accept the given JSON data, the following meta registration would be used.

{
   "meta": {
     "projects": [
       {
         "name": "WordPress",
         "website": "https://wordpress.org"
       },
       {
         "name": "BuddyPress",
         "website": "https://buddypress.org"
       }
     ]
   }
 }
register_post_meta(
     'post',
     'projects',
     array(
         'single'       => true,
         'type'         => 'array',
         'show_in_rest' => array(
             'schema' => array(
                 'items' => array(
                     'type'       => 'object',
                     'properties' => array(
                         'name'    => array(
                             'type' => 'string',
                         ),
                         'website' => array(
                             'type'   => 'string',
                             'format' => 'uri',
                         ),
                     ),
                 ),
             ),
         ),
     )
 );

Non-Single Metadata

Non-single meta fields have an array of values per post, instead of one value per post. Each of those values is stored in a separate row in the postmeta table.

The array and object data types can be used with non-single meta fields as well. For example, if the “release” meta key from earlier had single set to false, the following JSON data could be accepted.

{
   "meta": {
     "release": [
       {
         "version": "5.2",
         "artist": "Jaco"
       },
       {
         "version": "5.1",
         "artist": "Betty"
       }
     ]
   }
 }

This would result in two postmeta database rows. The first containing { "version": "5.2", "artist": "Jaco" } and the second containing { "version": "5.1", "artist": "Betty" }.

Similarly, the following data would be accepted for the “projects” example if it had set single to false.

{
   "meta": {
     "projects": [
       [
         "WordPress",
         "BuddyPress"
       ],
       [
         "bbPress"
       ]
     ]
   }
 }

This would result in two postmeta database rows. The first containing [ "WordPress", "BuddyPress" ] and the second containing [ "bbPress" ].

Invalidinvalid A resolution on the bug tracker (and generally common in software development, sometimes also notabug) that indicates the ticket is not a bug, is a support request, or is generally invalid. Stored Values

If the existing value for a meta field does not validate against the registered type and schema, the value for that meta field will be returned as null. This is a change in 5.3, where previously only the meta type was validated.

#5-3, #dev-notes, #rest-api

Dev Chat Summary: August 14

After the close of our every-two-weeks new contributor chat, the weekly coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. chat started at 2000 UTC, give or take a few minutes. (backscroll)

Announcements

Next Minor: 5.2.3

Next Major: 5.3

  • All but two focus lead type people are settled. An update post is upcoming (and will be shared by the end of the week regardless of whether those final two are settled or not).

Open Floor

To Do List from this Chat

  • First 5.2.3 bugbug A bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. scrub Thursday, August 15 @ 1700 UTC
  • If you want to help with the 5.2.3 minor releaseMinor Release A set of releases or versions having the same minor version number may be collectively referred to as .x , for example version 5.2.x to refer to versions 5.2, 5.2.1, 5.2.3, and all other versions in the 5.2 (five dot two) branch of that software. Minor Releases often make improvements to existing features and functionality. and weren’t mentioned above, you can indicate your interest in the comments of this post.

#summary #5-2-3 #5-3 #rest-api #auto-update

Rest API Chat Summary: June 27

This post summarizes the weekly REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. chat meeting for June 27, 2019. (Slack transcript). Weekly REST API component office hours are held every Thursday at 18:00 UTC in the #core-restapi room in the Make WordPress SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/..

Ticketticket Created for both bug reports and feature development on the bug tracker. Review

#43691 is close to being ready for commit. @timothybjacobs raised the question of how strict WordPress should be about enforcing the use of the 204 status code. @kadamwhite agreed that coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. shouldn’t be that stringent.

#43392 has received some more feedback. @timothybjacobs is working on a refreshed patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing.. @spacedmonkey wanted to know how the ticket would impact #43941. @kadamwhite didn’t think they’d conflictconflict A conflict occurs when a patch changes code that was modified after the patch was created. These patches are considered stale, and will require a refresh of the changes before it can be applied, or the conflicts will need to be resolved. and whichever ticket landed first would require the other to be adjusted.

#47443 came up in a recent REST API bugbug A bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. scrub. It touches post type capabilities which can be tricky. Feedback from developers with post type capabilities experience would be very helpful.

Menus Endpoint

@spacedmonkey has continued work on the Menus Endpoint. A discussion ensued about how to get better feedback on open PRs. Johnny is planning on writing up some basic test instructions. Subsequent PRs will hopefully be smaller and easier to test in the future.

The Menus Location endpoint was discussed. In particular, what endpoint should be responsible for assigning a menu to a menu location. @spacedmonkey‘s gut reaction is that menu-locations are like categories. You assign a categoryCategory The 'category' taxonomy lets you group posts / content together that share a common bond. Categories are pre-defined and broad ranging. on the post endpoint, so a menu location should assigned on the menu. @kadamwhite and @timothybjacobs had similar initial thoughts.

@kadamwhite brought up that it’s a bit of a flip from the existing UIUI User interface model, where you start with a location and then add a menu to it.

@timothybjacobs suggested modeling it after the existing posts controller, at least for the first iteration.

Upcoming Meetings

#rest-api

REST API Chat Summary: June 13th

This post summarizes the weekly REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. chat meeting for June 13, 2019. (Slack transcript). Weekly REST API component office hours are held every Thursday at 18:00 UTC in the #core-restapi room in the Make WordPress SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/..

Menus Endpoint

@spacedmonkey has continued work on the menus endpoint. Initial feedback was provided on the PR. The majority of the feedback has been addressed or is currently being worked on. It was decided to merge this PR soon and continue iterating in follow-up issues for the remaining feedback and decisions.

@jorgefilipecosta clarified how the GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ navigation project is storing data. The first versions are using blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. attributes to rapidly prototype the UXUX User experience. However, everything is open and using the REST API is a possibility.

@spacedmonkey brought up menu permissions. Ideally, some menu data would be publicly accessible, but that might show data that users don’t want to be public. @timothybjacobs suggested that to start, only menus that were attached to a menu location that was specifically marked as public would be exposed. A Github issue was opened for further discussion.

Upcoming Meetings

#rest-api