WP REST API – custom fields, authentication, and testing

So far, you’ve learned how to access core WordPress data using the REST API and the Backbone.js client, as well as how to create, delete, and update Posts. In this session, we will look at how to create or update custom field values in your REST API endpoints, the built-in authentication options for authenticating WP REST API requests, and how to test REST API routes and endpoints using a third party too.

Learning outcomes

  1. Create or update Post custom fields
  2. Authenticate with the REST API using Application Passwords
  3. Test REST API requests using Postman
  4. Locate additional information about the WP REST API

Comprehension questions

  1. What is the function name used to register custom fields?
  2. What is the name of the property on the Post model used to send custom field data in a WP REST API request?
  3. Which new functionality in WordPress allows you to set specific passwords for external applications?
View the video transcript

Hey there, and welcome to Learn WordPress.

In this tutorial, you’re going to learn a few more ways to interact with the WordPress REST API. You will learn how to create or update custom fields while creating or updating posts, and how to authenticate with the REST API using application passwords. You’ll also learn how to use the REST API testing tool to test your REST API routes and endpoints.

If you’ve never interacted with the WordPress REST API before, I recommend watching the Interacting with WordPress REST API tutorial first, and then coming back here. This tutorial builds on the code examples shared in the last tutorial, you can download the plugin that was created in that tutorial from this URL, and use it as the basis for this tutorial.

To review this plugin adds a new admin sub menu page to the Tools top level menu. And it uses the REST API to load the posts from the sites and display them in the top text area.

It also has a form that allows you to add a new post by entering the title and content fields and clicking the Add button, update a post by entering a post id, title, and content and clicking the Update button, and delete a post by entering the post id and clicking the Delete button. The plugin has a PHP file which handles the Admin menu and forms and a JavaScript file which interacts with the REST API using the Backbone.js client. Listing posts uses the post collection and creating and updating and deleting posts uses the post model. There are individual functions to handle each of these actions. And each function is called when the corresponding button is clicked.

Besides the default fields that exist on a post, WordPress also allows you to add and manage custom fields also known as metadata. These fields are often used on custom post types to store additional pieces of data that are specific to that post type. Under the hood, these custom fields are stored in the post meta table as a set of key value pairs attached to the post by the post ID. If you’ve ever worked with the add_post_meta, update_post_meta, and get_post_meta functions, you’ve accessing these custom fields. Beyond posts, WordPress also supports metadata on other data types, such as comments and users. You can read more about this in the MetaData API documentation on developer.wordpress.org.

The WordPress REST API allows you to create or update custom fields when creating or updating data. This is possible by passing an object of key value pairs to the meta property of the model you’re working with. However, in order to use a custom field, you have to register it first. This is done using the register_meta function. The key parameters required are the object type and meta key, and then an array of specific arguments. For example, if you wanted to add a custom field called url to the post type post, you would use the following code.

register_meta and then it will be applied to the post. And we’ll call the key url. Then we specify the array of arguments. And we should pass in things like whether or not it’s a single post meta. In this case, we’ll make a true the post meta type as case we’ll make it a string, the default value shall make an empty string and the show_in_rest argument will set to true.

This can be added to the root of the plugin PHP file and does not need to be wrapped in an action or a callback function. However, it is recommended to add it to something like the init action hook.

So we could say add_action init, specify a callback function to call when the init hook runs and then put the register_meta inside of this function, so it’s nice and neat.

It’s important to ensure that the show_in_rest property is set to true. Otherwise the custom field will not be available on the REST API. Once this is done, you can add a field to the form that creates Post to capture the URL value.

If we go down to the Add post, let’s copy the post title, because that is a text field. We’ll pop it underneath the post content and we’ll rename things to url.

Next, switch to the JavaScript file and update the submitPostFunction to get the url value.

This is the submitPostFunction. So let us add a post_url variable, document.getElementByID, wp-learn-post-url and we will return the value then pass the url value to the post model as part of the meta property. So inside of the post model object, a little bits we can now say, meta, and then create a new object passing the url and the post_url in the body.

Note that the meta property is an object so you can add as many key value pairs as you need. The key is the name of the custom field as specified in the register_meta function. Once you’ve done this, refresh the admin page and test adding a post with the url.

So let’s pop back to the page and refresh it. And then let’s add a post with a url and post with some content. And then some url. And we can add it.

To validate that the URL has been saved open a new browser window or tab and navigate to the post of the dashboard.

So we’ve got posts open here. So let’s navigate to all posts there is the post with the URL. And let’s take a look.

You should see the URL field in the Custom Fields area at the bottom of the editor screen.

Depending on your setup, you might need to enable the Custom Fields area. If you’re using the Block Editor, you can do this by clicking on the Options button. Clicking on Preferences, Panels, and enabling the Custom Fields toggle. This will require the editor to be reloaded. And then you can see the custom fields.

If you’re using the Classic Editor, click on the Screen Options button at the top of the window and enable the Custom Fields option.

By default, the WordPress REST API and the Backbone.js client use the same authentication cookie that is set in your browser as when you log into your WordPress dashboard. So if you’re a logged in user, you can access the API for creating update requests without needing to specify any authentication. This is how the Block Editor works. For example. If you wanted to build a separate application that allows specific users to create and update posts, you would need to provide a way for them to login. One way would be to make use of the default WordPress user login form and use the wp-login.php file to handle authentication.

Another way that’s now available to WordPress is something called application passwords. Application passwords can be set on a per user basis and are used to authenticate requests to the WordPress REST API. This allows you to let users access the API without having to share the password they use to log into the WordPress dashboard. Go ahead and create an application password for your user and save it to be used later. To do this, navigate to your user in the Users list and click on the user to edit it. Scroll down to the bottom of the screen under the application password section. Give the new application password a name and click the Add New Application Password button.

So let’s call this API testing and add new application password.

The password will be generated for you. Make sure to copy it as you won’t be able to see it again.

In this screen, you’re also able to revoke the password should it ever be leaked. Typically, your application will then need to ask the user for the username and this password. Let’s take a look at how these credentials can be used by introducing a tool to test REST API requests.

There are a number of tools available to test REST API requests. For example, if you use PhpStorm, it has a built in HTTP client. And if you use VS Code, there are extensions like Postcode that you can install. There’s also standalone tools like Hopscotch, and Postman. You can even test with your REST API endpoints using the curl command in your terminal. For the purposes of this tutorial, we’ll be using Postman.

You can download the Postman app from the Postman website. The current version at the time of this recording is version 10.8.6. By default, Postman will create an initial workspace to store your request collections. Once opened, click on the Create Collection button to create a new collection where you can add multiple requests to test

Let’s say REST API collection.

You can give the collection a name to differentiate it from other collections. Inside the collection, click the Add Request button.

This will open a new request where you can give the request a unique name.

So let’s say GET posts.

Then enter the URL to your local posts end point and click the Send button.

So in our case, it will be learnpress.test/wp-json/wp/v2/posts and click the Send button.

The request will be made and the JSON response will be parsed and displayed in the response area.

Now create a new request and enter the same URL to the post endpoint. But this time change the request method to POST.

So what we can do is we can duplicate this request and simply change the name of the request and change the method and hit send.

When you create the request, you’ll be presented with an error message because you’re not authenticated. To authenticate the request, click on the Authorization tab and select Basic auth from the drop down.

Then enter your username and password and click the Save button.

So in our case, the username is admin. And we’ll need to paste the application password we created earlier. And then save this request and then send it.

This time you don’t get the same error because you are authenticated. So this means we can create posts if we pass in the right data. Go ahead and create a new post by clicking on the Body tab in the request and selecting the Raw radio button.

So body, raw.

Then select JSON from the drop down and enter the following JSON object.

JSON. And we will open a new JSON object. And now we can specify the REST API fields as we did in the Backbone.js client. So we can say my new testing post. And for content. I can just say my new testing post content and let’s make sure to give it a status of Publish. And let’s also pass in the meta object which is the URL custom field and we will just say something like example.com

Hit Send again and the post will be created returning the JSON response of the new post.

So let’s send this and there is the new post information.

To be sure, go ahead and check the post in the WordPress dashboard, you should see the post created with the URL custom field.

Let’s switch over to posts. There’s a new testing post. And there is the example.

Using a tool like Postman to test REST API endpoints is a great way to save time by ensuring that the data you intend to send is formatted correctly, and that the request is being made to the correct endpoint. It’s also extremely useful when extending the REST API.

For more information on interacting with the WordPress REST API as well as how to extend it, check out the WordPress REST API handbook at developer.wordpress.org.

Happy coding

Introduction

Hey there, and welcome to Learn WordPress.

In this tutorial, you’re going to learn more ways to interact with the WordPress REST API.

You will learn how create or update custom fields when creating or updating Posts, and how to authenticate with the REST API using Application Passwords. You’ll also learn how to use a REST API testing tool to test WP REST API routes and endpoints.

If you’ve never interacted with the WP REST API before, I recommend watching the Interacting with the WP REST API tutorial first, and then coming back here.

Example code

This tutorial builds on the code examples shared in the Interacting the WordPress REST API tutorial. You can download the plugin that was created in that tutorial from this URL, and use it as the basis for this tutorial.

https://github.com/jonathanbossenger/wp-learn-rest-api/releases/download/0.0.3-v2/wp-learn-rest-api.0.0.3-v2.zip

To review, this plugin adds a new admin submenu page to the WordPress Tools menu, and uses the WP REST API to load the posts from the site, and display them in a textarea. It also has a form that allows you to create a new post, by entering the title and content fields and clicking the add button, update a post by entering a post id, title and content and clicking the update button, and delete a post by entering the post id and clicking the delete button.

The PHP code handles the menu registration and the admin page form. The JavaScript code that powers this makes use of the Backbone.js client that ships with WordPress. Listing posts uses the Posts collection, and creating updating and deleting posts uses the Posts model. There are individual functions to handle each of these actions, and each function is called when the corresponding button is clicked.

Working with custom fields

Besides the default fields that exist on a Post, WordPress also allows you to add and manage custom fields, also known as metadata. These fields are often used on custom post types, to store additional pieces of data that are specific to that post type. Under the hood, these custom fields are stored in the postmeta table, as a set of key/value pairs attached to the post by the post id.

If you’ve ever worked with the add_post_meta, update_post_meta and get_post_meta functions, you were accessing the these custom fields.

Beyond Posts, WordPress also supports metadata on other data types, such as comments and users. You can read more about this in the Metadata API documentation.

The WP REST API allows you to create or update custom fields when creating or updating data.

This is possible by passing an object of key/value pairs to the meta property of the model you’re working with.

However, in order to use a custom field, you have to register it first. This is done using the register_meta function.

For example, if you wanted to add a custom field called “url” to the post type “post”, you would use the following code:

    register_meta(
        'post',
        'url',
        array(
            'single'       => true,
            'type'         => 'string',
            'default'      => '',
            'show_in_rest' => true,
        )
    );

This can be added to the root of the plugin PHP file, and does not need to be wrapped in an action hook callback function. However, it’s recommended to add it to something like the init action hook.

add_action( 'init', 'wp_learn_register_meta' );
function wp_learn_register_meta(){
    register_meta(
        'post',
        'url',
        array(
            'single'       => true,
            'type'         => 'string',
            'default'      => '',
            'show_in_rest' => true,
        )
    );
}

It’s important to ensure that the show_in_rest property is set to true, otherwise the custom field will not be available in the REST API.

Once this is done, go ahead and add a field to the form that creates a post, to capture the url value:

<div>
    <label for="wp-learn-post-url">Post Url</label>
    <input type="text" id="wp-learn-post-url" placeholder="Url">
</div>

Next, switch to the JavaScript file, and update the submitPost function to get the url value:

const url = document.getElementById( 'wp-learn-post-url' ).value;

Then, pass the url value to the Post model, as part of the meta property:

        meta: {
            url: url
        }

Note that the meta property is an object, so you can add as many key/value pairs as you need. The key is the name of the custom field, as specified in the register_meta function.

Once you’ve done this, refresh the admin page, and test adding a post with the url.

To validate that the url has been saved, open a new browser window or tab, and navigate to the post in the WP dashboard. You should see the url field in the Custom Fields area, at the bottom of the editor screen.

Depending on your set-up, you might need to enable the Custom Fields area. If you’re using the block editor, you can do this by clicking on the Options button, selecting Preferences, clicking on Panels, and enabling the Custom Fields toggle. This will require the editor to be reloaded.

If you’re using the classic editor, click on the Screen Options button, and enable the Custom Fields option.

Authentication

By default, the WP REST API uses the same authentication cookie that is set in your browser as when you log into your WordPress dashboard. So if you’re a logged-in user, you can access the API for create and update requests without needing to specific any authentication. This is how the block editor works, for example.

If you wanted to build a separate application that allows specific users to create and update posts, you would need to provide a way for them to log in. One way would be to make use of the default WordPress user login form, and use the wp-login.php file to handle the authentication. Another way that’s now available to WordPress is Application passwords.

Application passwords can be set on a per-user basis, and are used to authenticate requests to the WP REST API. This allows you to let users access the API without having to share the password they use to login to the WordPress dashboard.

Go ahead and create an application password for your user, and save it to be used later. To do this, navigate to your user in the Users list, and click on the User to edit it. Scroll down to the bottom of the screen, under the Application Passwords section. Give the new application password a name and click ADd New Application Password.

The password will be generated for you. Make sure to copy it, as you won’t be able to see it again. In this screen you are also able to revoke the password, should it ever be leaked.

Typically, your application would then need to ask the user for their username and password.

Let’s take a look at how these credentials can be used, by introducing a tool to test REST API requests.

Postman

There are a number of tools available to test REST API requests. For example, if you use PhpStorm, it has a built-in HTTP client, and if you use VS Code, there are extensions like https://marketplace.visualstudio.com/items?itemName=rohinivsenthil.postcode. There are also standalone tools like Hoppscotch, and Postman. You can even test your REST API endpoints using the curl command in your terminal.

For the purposes of this tutorial, we’ll be using Postman.

You can download Postman from the Postman website. The current version at the time of this recording is Version 10.8.6. By default, Postman will create an initial workspace, to store your request collections.

Once installed, open Postman, and click on the Create Collection button. This will create a new collection, where you can add multiple requests to test.

You can give the collecting a name to differentiate it from other collections. Inside the collection click the Add a request button.

This will open a new request, where you can give the request a unique name. Then, enter the url to your local posts endpoint, and click the Send button.

https://example.test/wp-json/wp/v2/posts

The request will be made, and the JSON response will be parsed and displayed in the response area.

Now, create a new request, and enter the same url to the posts endpoint, but this time change the request method to POST, and hit send.

This time you’ll be presented with an error message, because you’re not authenticated.

To authenticate the request, click on the Authorization tab, and select Basic Auth from the dropdown. Then, enter your username and password, and click the Save button.

This time you don’t get the same error, because you’re not authenticated. So you can create posts.

Go ahead and create one, by clicking on the Body tab in the request, and selecting the raw radio button. Then, select JSON from the dropdown, and enter the following JSON:

{
    "title": "My Postman Post",
    "content": "This is my Postman post",
    "status": "publish",
    "meta": {
        "url": "https://postman.com"
    }
}

Hit send again, and the post will be created, returning the JSON response of the new post.

To be sure, go ahead and check the post in the WP dashboard, and you should see the post, with the url custom field.

Using a tool like Postman to test REST API endpoints is a great way to save time, by ensuring that the data you intend to send is formatted correctly, and that the request is being made to the correct endpoint. It’s also extremely useful when extending the WP REST API.

For more information in interacting with the WP REST API, as well as how to extend it, check out the WP REST API Handbook at developer.wordpress.org.

Happy coding!

Length 16 minutes
Language English
Subtitles English (South Africa)

Suggestions

Found a typo, grammar error or outdated screenshot? Contact us.