WordPress REST API

Summary: Learning about REST API its different methods, WordPress REST API and its key concepts.

REST API

REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing.

REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology because REST uses less bandwidth, simple and flexible making it more suitable for internet usage. It’s used to fetch or give some information from a web service. All communication done via REST API uses only HTTP request.

A request is sent from client to server in the form of a web URL as HTTP GET or POST or PUT or DELETE request. After that, a response comes back from the server in the form of a resource which can be anything like HTML, XML, Image, or JSON. But now JSON is the most popular format being used in Web Services.

Methods

GET: The HTTP GET method is used to read (or retrieve) a representation of a resource. In the safe path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).

POST: The POST verb is most often utilized to create new resources. In particular, it’s used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource. On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.

PUT: It is used for updating the capabilities. However, PUT can also be used to create a resource in the case where the resource ID is chosen by the client instead of by the server. In other words, if the PUT is to a URI that contains the value of a non-existent resource ID. On successful update, return 200 (or 204 if not returning any content in the body) from a PUT. If using PUT for create, return HTTP status 201 on successful creation. PUT is not safe operation but it’s idempotent.

PATCH: It is used to modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource. This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither safe nor idempotent.

DELETE: It is used to delete a resource identified by a URI. On successful deletion, return HTTP status 200 (OK) along with a response body.

WordPress REST API

The WordPress REST API provides an interface for applications to interact with our WordPress site by sending and receiving data as JSON (JavaScript Object Notation) objects. It is the foundation of the WordPress Block Editor, and can likewise enable our theme, plugin or custom application to present new, powerful interfaces for managing and publishing our site content.

Using the WordPress REST API we can create a plugin to provide an entirely new admin experience for WordPress, build a brand new interactive front-end experience, or bring your WordPress content into completely separate applications.

Routes & Endpoints

In the context of the WordPress REST API a route is a URI which can be mapped to different HTTP methods. The mapping of an individual HTTP method to a route is known as an endpoint.

As an example, if we make a GET request to the URI http://oursite.com/wp-json/ we are returned a JSON response showing what routes are available, and what endpoints are available within each route.

/wp-json/ is a route, and when that route receives a GET request then that request is handled by the endpoint which displays what is known as the index for the WordPress REST API.

The route wp-json/wp/v2/posts by contrast has a GET endpoint which returns a list of posts, but also a POST endpoint which accepts authenticated requests to create new posts.

Requests

A REST API request is represented within WordPress by an instance of the WP_REST_Request class, which is used to store and retrieve information for the current request. A WP_REST_Request object is automatically generated when you make an HTTP request to a registered API route.

The data specified in this object (derived from the route URI or the JSON payload sent as a part of the request) determines what response you will get back out of the API.

Requests are usually submitted remotely via HTTP but may also be made internally from PHP within WordPress plugin or theme code.

Responses

Responses are the data you get back from the API. The WP_REST_Response class provides a way to interact with the response data returned by endpoints. Responses return the requested data, or can also be used to return errors if something goes wrong while fulfilling the request.

Schema

Each endpoint requires a particular structure of input data, and returns data using a defined and predictable structure. Those data structures are defined in the API Schema.

The schema structures API data and provides a comprehensive list of all of the properties the API can return and which input parameters it can accept.

Controller Classes

Controller classes unify and coordinate all these various moving parts within a REST API response cycle. With a controller class you can manage the registration of routes & endpoints, handle requests, utilize schema, and generate API responses.

Custom Endpoint

function my_custom_endpoint() {
    register_rest_route('myplugin/v1', '/data/', array(
        'methods' => 'GET',
        'callback' => 'my_custom_endpoint_callback',
    ));
}
add_action('rest_api_init', 'my_custom_endpoint');

function my_custom_endpoint_callback() {
    return array('message' => 'Hello, this is a custom endpoint!');
}

Extending Existing Endpoint

function my_custom_post_meta() {
    register_rest_field('post', 'my_custom_field', array(
        'get_callback' => 'my_custom_field_get_callback',
        'update_callback' => 'my_custom_field_update_callback',
        'schema' => null,
    ));
}
add_action('rest_api_init', 'my_custom_post_meta');

function my_custom_field_get_callback($object, $field_name, $request) {
    return get_post_meta($object['id'], $field_name, true);
}

function my_custom_field_update_callback($value, $post, $field_name) {
    return update_post_meta($post->ID, $field_name, sanitize_text_field($value));
}
«
»

Leave a Reply

Your email address will not be published. Required fields are marked *