Skip to content

WordPress REST API Client for Java - Samples

Creating a Page

Create and publish a new WordPress page using the REST API.

This sample demonstrates how to:

  • Configure a WpRestClient using either Apache HttpClient or OkHttp.
  • Authenticate using either Basic Authentication or JWT Authentication.
  • Build a WpPageCreateUpdateRequest using the fluent builder API.
  • Set common page attributes such as the title, content, status, author, slug, excerpt, comment status, and ping status.
  • Create the page and receive the resulting WpPage instance returned by the WordPress REST API.
  • Access the ID of the newly created page for further processing.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/pages/CreatePage.java
package io.github.evisentin.wordpress.rest.client.samples.code.pages;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPage;
import io.github.evisentin.wordpress.rest.client.domain.model.enums.WpOpenClosed;
import io.github.evisentin.wordpress.rest.client.domain.model.requests.WpPageCreateUpdateRequest;
import io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder;

import static io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPageStatus.PUBLISH;
import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.AuthenticationType.BASIC_AUTH;
import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.Implementation.APACHE;

/**
 * Demonstrates how to create a new WordPress page.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Build a {@link WpPageCreateUpdateRequest} using the builder API.</li>
 *     <li>Set common page attributes such as title, content, status, author, slug, excerpt,
 *     comment status, and ping status.</li>
 *     <li>Create the page using the WordPress REST API.</li>
 *     <li>Access the returned {@link WpPage} instance.</li>
 * </ul>
 * <p>
 * The request intentionally sets a number of optional fields to demonstrate the available customization options.
 * Most of these attributes are optional and, if omitted, WordPress automatically supplies sensible defaults where
 * applicable (for example, the slug, excerpt, and current authenticated user as the author).
 * <p>
 * Before running this sample, configure the connection details in {@link SampleClientBuilder} so they match your
 * WordPress installation.
 */
public class CreatePage {
    public static void main(String[] args) {

        // Choose the desired HTTP client implementation and authentication mechanism.
        //
        // Supported combinations:
        //   buildClientFor(BASIC_AUTH, APACHE)
        //   buildClientFor(JWT,        APACHE)
        //   buildClientFor(BASIC_AUTH, OK_HTTP)
        //   buildClientFor(JWT,        OK_HTTP)
        final WpRestClient restClient = SampleClientBuilder.buildClientFor(BASIC_AUTH, APACHE);

        WpPageCreateUpdateRequest createRequest =
                WpPageCreateUpdateRequest.builder()
                                         .withTitle("The title of my page")
                                         .withStatus(PUBLISH) // we want to create and publish it immediately
                                         .withContent("""
                                                 Lorem ipsum dolor sit amet consectetur adipiscing elit.

                                                 Quisque faucibus ex sapien vitae pellentesque sem placerat.

                                                 In id cursus mi pretium tellus duis convallis.
                                                 """)
                                         .withAuthorId(100L) // if not specified, the current user's ID is put automatically by WordPress
                                         .withCommentStatus(WpOpenClosed.OPEN) // not mandatory, here to show it
                                         .withPingStatus(WpOpenClosed.CLOSED) // not mandatory, here to show it
                                         .withSlug("something") // generated by WordPress if not passed
                                         .withExcerpt("Lorem ipsum dolor sit") // generated by WordPress if not passed
                                         // see WpPageCreateUpdateRequest Javadoc for other attributes
                                         .build();

        final WpPage wpPage = restClient.pages().create(createRequest);

        System.out.println("Page created with id=" + wpPage.getId());
    }
}

Retrieving a Page

Retrieve a single WordPress page by its identifier using the REST API.

This sample demonstrates how to:

  • Configure a WpRestClient using either Apache HttpClient or OkHttp.
  • Authenticate using either Basic Authentication or JWT Authentication.
  • Retrieve a page by its ID.
  • Specify the desired WpContext (VIEW, EDIT, or EMBED) to control the information returned by the API.
  • Retrieve a password-protected page by supplying its password.
  • Receive the resulting WpPage instance returned by the WordPress REST API.
  • Handle common error scenarios such as unauthorized access, insufficient permissions, or a non-existent page.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/pages/GetPage.java
package io.github.evisentin.wordpress.rest.client.samples.code.pages;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPage;
import io.github.evisentin.wordpress.rest.client.domain.model.enums.WpContext;
import io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder;

import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.AuthenticationType.BASIC_AUTH;
import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.Implementation.APACHE;

/**
 * Demonstrates how to retrieve a single WordPress page.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Retrieve a page by its identifier.</li>
 *     <li>Specify the desired {@link WpContext} for the response.</li>
 *     <li>Retrieve a password-protected page by supplying its password.</li>
 *     <li>Access the returned {@link WpPage} instance.</li>
 * </ul>
 * <p>
 * The example shows both retrieving a standard page and accessing a password-protected page.
 * The {@link WpContext} controls which fields are included in the response. Public pages are typically retrieved using
 * {@code VIEW}, while authenticated users can request {@code EDIT} to obtain additional information.
 * <p>
 * Depending on the requested page and the current user's permissions, the client may throw exceptions such as:
 * <ul>
 *     <li>{@code WpForbiddenException} if access to the page is denied.</li>
 *     <li>{@code WpNotFoundException} if the page does not exist.</li>
 *     <li>{@code WpUnauthorizedException} if authentication is required or invalid.</li>
 * </ul>
 * <p>
 * Before running this sample, configure the connection details in {@link SampleClientBuilder} so they match your
 * WordPress installation.
 */
public class GetPage {
    public static void main(String[] args) {

        // Choose the desired HTTP client implementation and authentication mechanism.
        //
        // Supported combinations:
        //   buildClientFor(BASIC_AUTH, APACHE)
        //   buildClientFor(JWT,        APACHE)
        //   buildClientFor(BASIC_AUTH, OK_HTTP)
        //   buildClientFor(JWT,        OK_HTTP)
        final WpRestClient restClient = SampleClientBuilder.buildClientFor(BASIC_AUTH, APACHE);

        final WpContext wpContext = WpContext.EDIT; /* or WpContext.VIEW, or WpContext.EMBED */

        // Given page id=100L exists;
        final WpPage wpPage = restClient.pages().get(100L, wpContext);

        // Given page id=200L exists and has been created with a password;
        final WpPage wpPageWithPassword = restClient.pages().get(100L, wpContext, "my-password");

        // PLEASE NOTE: you might get
        // - WpForbiddenException
        // - WpNotFoundException
        // - WpUnauthorizedException
    }
}

Deleting a Page

Delete a WordPress page using the REST API, either by moving it to the trash or by permanently removing it.

This sample demonstrates how to:

  • Configure a WpRestClient using either Apache HttpClient or OkHttp.
  • Authenticate using either Basic Authentication or JWT Authentication.
  • Move a page to the WordPress trash, allowing it to be restored later.
  • Permanently delete a page and receive a WpPageDeletionResponse.
  • Inspect the deletion result and determine whether the page was successfully deleted.
  • Access summary information about the deleted page, such as its ID, title, slug, status, and content.
  • Handle common error scenarios such as unauthorized access, insufficient permissions, or a non-existent page.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/pages/DeletePage.java
package io.github.evisentin.wordpress.rest.client.samples.code.pages;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPage;
import io.github.evisentin.wordpress.rest.client.domain.model.responses.WpPageDeletionResponse;
import io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder;

import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.AuthenticationType.BASIC_AUTH;
import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.Implementation.APACHE;

/**
 * Demonstrates how to delete a WordPress page.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Move a page to the WordPress trash.</li>
 *     <li>Permanently delete a page.</li>
 *     <li>Inspect the returned {@link WpPageDeletionResponse}.</li>
 *     <li>Access information about the deleted page through the response summary.</li>
 * </ul>
 * <p>
 * The sample demonstrates the two deletion modes supported by the WordPress REST API. Calling {@code trash()} moves
 * the page to the trash, allowing it to be restored later. Calling {@code delete()} permanently removes the page
 * and returns a {@link WpPageDeletionResponse} containing the deletion status together with a summary of the deleted page.
 * <p>
 * Depending on the requested page and the current user's permissions, the client may throw exceptions such as:
 * <ul>
 *     <li>{@code WpForbiddenException} if the current user is not allowed to delete the page.</li>
 *     <li>{@code WpNotFoundException} if the page does not exist.</li>
 *     <li>{@code WpUnauthorizedException} if authentication is required or invalid.</li>
 * </ul>
 * <p>
 * Before running this sample, configure the connection details in {@link SampleClientBuilder} so they match your
 * WordPress installation.
 */
public class DeletePage {
    public static void main(String[] args) {

        // Choose the desired HTTP client implementation and authentication mechanism.
        //
        // Supported combinations:
        //   buildClientFor(BASIC_AUTH, APACHE)
        //   buildClientFor(JWT,        APACHE)
        //   buildClientFor(BASIC_AUTH, OK_HTTP)
        //   buildClientFor(JWT,        OK_HTTP)
        final WpRestClient restClient = SampleClientBuilder.buildClientFor(BASIC_AUTH, APACHE);

        // Given page id=100L exists;

        // here the page is marked as ( wpPage.getStatus() == WpPageStatus.TRASH), but still exists, it is possible to recover it.
        final WpPage wpPage = restClient.pages().trash(100L);

        // here the page is permanently deleted.
        final WpPageDeletionResponse deletionResponse = restClient.pages().delete(100L);

        final boolean deleted = deletionResponse.isDeleted();// true/false
        final WpPageDeletionResponse.Summary previous = deletionResponse.getPrevious();
        // previous.getId();
        // previous.getTitle();
        // previous.getContent();
        // previous.getExcerpt();
        // previous.getSlug();
        // previous.getStatus();
        // previous.getLink();

        // PLEASE NOTE: you might get
        // - WpForbiddenException
        // - WpNotFoundException
        // - WpUnauthorizedException
    }
}

Updating a Page

Update an existing WordPress page using the REST API.

This sample demonstrates how to:

  • Configure a WpRestClient using either Apache HttpClient or OkHttp.
  • Authenticate using either Basic Authentication or JWT Authentication.
  • Build a WpPageCreateUpdateRequest using the fluent builder API.
  • Perform a partial update by specifying only the page attributes that should change.
  • Update an existing page by its ID and receive the resulting WpPage instance returned by the WordPress REST API.
  • Change common page attributes such as the title and publication status while leaving all unspecified fields unchanged.
  • Handle common error scenarios such as unauthorized access, insufficient permissions, or a non-existent page.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/pages/UpdatePage.java
package io.github.evisentin.wordpress.rest.client.samples.code.pages;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPage;
import io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPageStatus;
import io.github.evisentin.wordpress.rest.client.domain.model.requests.WpPageCreateUpdateRequest;
import io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder;

import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.AuthenticationType.BASIC_AUTH;
import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.Implementation.APACHE;

/**
 * Demonstrates how to update an existing WordPress page.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Build a {@link WpPageCreateUpdateRequest} containing only the fields to be updated.</li>
 *     <li>Update an existing page using its identifier.</li>
 *     <li>Access the returned {@link WpPage} instance.</li>
 * </ul>
 * <p>
 * The request performs a partial update: only the fields specified in the {@link WpPageCreateUpdateRequest} are
 * modified, while all other page attributes remain unchanged. In this example, the page title is updated and its
 * status is changed from {@code DRAFT} to {@code PUBLISH}.
 * <p>
 * Depending on the requested page and the current user's permissions, the client may throw exceptions such as:
 * <ul>
 *     <li>{@code WpForbiddenException} if the current user is not allowed to update the page.</li>
 *     <li>{@code WpNotFoundException} if the page does not exist.</li>
 *     <li>{@code WpUnauthorizedException} if authentication is required or invalid.</li>
 * </ul>
 * <p>
 * Before running this sample, configure the connection details in {@link SampleClientBuilder} so they match your
 * WordPress installation.
 */
public class UpdatePage {
    public static void main(String[] args) {

        // Choose the desired HTTP client implementation and authentication mechanism.
        //
        // Supported combinations:
        //   buildClientFor(BASIC_AUTH, APACHE)
        //   buildClientFor(JWT,        APACHE)
        //   buildClientFor(BASIC_AUTH, OK_HTTP)
        //   buildClientFor(JWT,        OK_HTTP)
        final WpRestClient restClient = SampleClientBuilder.buildClientFor(BASIC_AUTH, APACHE);

        // Given page id=100L exists and has DRAFT status;

        // All the fields not present in the updateRequest shall remain unchanged in the page after the update.
        final WpPageCreateUpdateRequest updateRequest =
                WpPageCreateUpdateRequest.builder()
                                         .withTitle("My new title")
                                         .withStatus(WpPageStatus.PUBLISH) // it was DRAFT before
                                         .build();

        final WpPage updatedPage = restClient.pages().update(100L, updateRequest);

        // PLEASE NOTE: you might get
        // - WpForbiddenException
        // - WpNotFoundException
        // - WpUnauthorizedException
    }
}

Listing Pages

Retrieve a paginated list of WordPress pages using the REST API.

This sample demonstrates how to:

  • Configure a WpRestClient using either Apache HttpClient or OkHttp.
  • Authenticate using either Basic Authentication or JWT Authentication.
  • Filter posts by status (Draft, Pending, and Published).
  • Request a specific page of results.
  • Read pagination metadata such as the total number of items and whether additional pages are available.
  • Iterate over the returned pages and access common fields such as the ID, title, slug, and status.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/pages/ListPages.java
package io.github.evisentin.wordpress.rest.client.samples.code.pages;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPage;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPagedResponse;
import io.github.evisentin.wordpress.rest.client.domain.model.query.WpPageQuery;
import io.github.evisentin.wordpress.rest.client.domain.model.query.WpPaginationQuery;
import io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder;

import static io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPageStatus.DRAFT;
import static io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPageStatus.PENDING;
import static io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPageStatus.PUBLISH;
import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.AuthenticationType.BASIC_AUTH;
import static io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder.Implementation.APACHE;

/**
 * Demonstrates how to retrieve a paginated list of WordPress pages.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Filter pages using a {@link WpPageQuery}.</li>
 *     <li>Request a page of results using {@link WpPaginationQuery}.</li>
 *     <li>Access pagination metadata.</li>
 *     <li>Iterate over the returned {@link WpPage} instances.</li>
 * </ul>
 * <p>
 * Before running this sample, configure the connection details in {@link SampleClientBuilder} so they match your
 * WordPress installation.
 */
public class ListPages {
    public static void main(String[] args) {

        // Choose the desired HTTP client implementation and authentication mechanism.
        //
        // Supported combinations:
        //   buildClientFor(BASIC_AUTH, APACHE)
        //   buildClientFor(JWT,        APACHE)
        //   buildClientFor(BASIC_AUTH, OK_HTTP)
        //   buildClientFor(JWT,        OK_HTTP)
        final WpRestClient restClient = SampleClientBuilder.buildClientFor(BASIC_AUTH, APACHE);

        // WpPageQuery provides many attributes for filtering pages. This example filters by page status only.
        // Refer to the class Javadoc for a complete description of all supported query parameters.
        final WpPageQuery query = WpPageQuery.builder()
                                             .withStatus(DRAFT)
                                             .withStatus(PUBLISH)
                                             .withStatus(PENDING)
                                             .build();
        final WpPaginationQuery pagingQuery = new WpPaginationQuery(1, 10);

        final WpPagedResponse<WpPage> pagedResponse =
                restClient.pages()
                          .list(pagingQuery, query);

        // Print pagination information.
        System.out.println("Page number   : " + pagedResponse.pageNumber());
        System.out.println("Items per page: " + pagedResponse.itemsPerPage());
        System.out.println("Total items   : " + pagedResponse.totalItems());
        System.out.println("Has next page : " + pagedResponse.hasNextPage());
        System.out.println("Is empty      : " + pagedResponse.isEmpty());

        // Print returned pages.
        pagedResponse.items()
                     .forEach(page ->
                             System.out.printf(
                                     "[id=%d] [title='%s'] [slug='%s'] [status='%s'] %n",
                                     page.getId(),
                                     page.getTitle().getRendered(),
                                     page.getSlug(),
                                     page.getStatus()
                             )
                     );
    }
}