Skip to content

WordPress REST API Client for Java - Samples

Creating a Category

Create a new WordPress category 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 WpCategoryCreateUpdateRequest using the fluent builder API.
  • Set common category attributes such as the name, slug, description, and parent category.
  • Create the category and receive the resulting WpCategory instance returned by the WordPress REST API.
  • Access the ID of the newly created category for further processing.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/categories/CreateCategory.java
package io.github.evisentin.wordpress.rest.client.samples.code.categories;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpCategory;
import io.github.evisentin.wordpress.rest.client.domain.model.requests.WpCategoryCreateUpdateRequest;
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 create a new WordPress category.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Build a {@link WpCategoryCreateUpdateRequest} using the builder API.</li>
 *     <li>Set common category attributes such as the name, slug, description, and parent category.</li>
 *     <li>Create the category using the WordPress REST API.</li>
 *     <li>Access the returned {@link WpCategory} 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).
 * <p>
 * Before running this sample, configure the connection details in {@link SampleClientBuilder} so they match your
 * WordPress installation.
 */
public class CreateCategory {
    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);

        WpCategoryCreateUpdateRequest createRequest =
                WpCategoryCreateUpdateRequest.builder()
                                             .withName("My Category")
                                             .withSlug("my-category") // if not provided, it is computed by WordPress
                                             .withDescription("The description of my category")
                                             //.withParentId(1000L) // in case you want to add a parent.
                                             .build();

        final WpCategory wpCategory = restClient.categories().create(createRequest);

        System.out.println("Category created with id=" + wpCategory.getId());
    }
}

Retrieving a Category

Retrieve a single WordPress category 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 category by its ID.
  • Specify the desired WpContext (VIEW, EDIT, or EMBED) to control the information returned by the API.
  • Receive the resulting WpCategory instance returned by the WordPress REST API.
  • Handle common error scenarios such as unauthorized access, insufficient permissions, or a non-existent category.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/categories/GetCategory.java
package io.github.evisentin.wordpress.rest.client.samples.code.categories;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpCategory;
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 category.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Retrieve a category by its identifier.</li>
 *     <li>Specify the desired {@link WpContext} for the response.</li>
 *     <li>Access the returned {@link WpCategory} instance.</li>
 * </ul>
 * <p>
 * The {@link WpContext} controls which fields are included in the response. Public categories are typically retrieved
 * using {@code VIEW}, while authenticated users can request {@code EDIT} to obtain additional information.
 * <p>
 * Depending on the requested category and the current user's permissions, the client may throw exceptions such as:
 * <ul>
 *     <li>{@code WpForbiddenException} if access to the category is denied.</li>
 *     <li>{@code WpNotFoundException} if the category 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 GetCategory {
    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 category id=100L exists;
        final WpCategory category = restClient.categories().get(100L, wpContext);

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

Deleting a Category

Delete a WordPress category 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.
  • Permanently delete a category and receive a WpCategoryDeletionResponse.
  • Inspect the deletion result and determine whether the category was successfully deleted.
  • Access summary information about the deleted category, such as its ID, name, slug, description, taxonomy, and link.
  • Handle common error scenarios such as unauthorized access, insufficient permissions, or a non-existent category.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/categories/DeleteCategory.java
package io.github.evisentin.wordpress.rest.client.samples.code.categories;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.responses.WpCategoryDeletionResponse;
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 category.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Permanently delete a category.</li>
 *     <li>Inspect the returned {@link WpCategoryDeletionResponse}.</li>
 *     <li>Access information about the deleted category through the response summary.</li>
 * </ul>
 * <p>
 * Categories are permanently deleted by the WordPress REST API. The {@code delete()} operation returns a
 * {@link WpCategoryDeletionResponse} containing the deletion status together with a summary of the deleted category.
 * <p>
 * Depending on the requested category 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 category.</li>
 *     <li>{@code WpNotFoundException} if the category 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 DeleteCategory {
    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 category id=100L exists;

        final WpCategoryDeletionResponse deletionResponse = restClient.categories().delete(100L);

        final boolean deleted = deletionResponse.isDeleted(); // true/false
        final WpCategoryDeletionResponse.Summary previous = deletionResponse.getPrevious();
        // previous.getId();
        // previous.getCount();
        // previous.getDescription();
        // previous.getName();
        // previous.getSlug();
        // previous.getTaxonomy();
        // previous.getLink();

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

Updating a Category

Update an existing WordPress category 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 WpCategoryCreateUpdateRequest using the fluent builder API.
  • Perform a partial update by specifying only the category attributes that should change.
  • Update an existing category by its ID and receive the resulting WpCategory instance returned by the WordPress REST API.
  • Change common category attributes such as the name, slug, description, and parent category while leaving all unspecified fields unchanged.
  • Handle common error scenarios such as unauthorized access, insufficient permissions, or a non-existent category.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/categories/UpdateCategory.java
package io.github.evisentin.wordpress.rest.client.samples.code.categories;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpCategory;
import io.github.evisentin.wordpress.rest.client.domain.model.requests.WpCategoryCreateUpdateRequest;
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 category.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Build a {@link WpCategoryCreateUpdateRequest} containing only the fields to be updated.</li>
 *     <li>Update an existing category using its identifier.</li>
 *     <li>Access the returned {@link WpCategory} instance.</li>
 * </ul>
 * <p>
 * The request performs a partial update: only the fields specified in the
 * {@link WpCategoryCreateUpdateRequest} are modified, while all other category attributes remain unchanged. In this
 * example, the category description is updated.
 * <p>
 * Depending on the requested category 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 category.</li>
 *     <li>{@code WpNotFoundException} if the category 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 UpdateCategory {
    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 category id=100L exists

        // All the fields not present in the updateRequest shall remain unchanged in the category after the update.
        final WpCategoryCreateUpdateRequest updateRequest =
                WpCategoryCreateUpdateRequest.builder()
                                             .withDescription("My new description")
                                             .build();

        final WpCategory updatedCategory = restClient.categories().update(100L, updateRequest);

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

Listing Categories

Retrieve a paginated list of WordPress categories 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 categories using one or more query parameters, such as the associated post.
  • 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 categories and access common fields such as the ID, name, slug, and description.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/categories/ListCategories.java
package io.github.evisentin.wordpress.rest.client.samples.code.categories;

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpCategory;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPagedResponse;
import io.github.evisentin.wordpress.rest.client.domain.model.query.WpCategoryQuery;
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.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 categories.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Filter categories using a {@link WpCategoryQuery}.</li>
 *     <li>Request a page of results using {@link WpPaginationQuery}.</li>
 *     <li>Access pagination metadata.</li>
 *     <li>Iterate over the returned {@link WpCategory} instances.</li>
 * </ul>
 * <p>
 * Before running this sample, configure the connection details in {@link SampleClientBuilder} so they match your
 * WordPress installation.
 */
public class ListCategories {
    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);

        // WpCategoryQuery provides many attributes for filtering categories. This example filters by post id only.
        // Refer to the class Javadoc for a complete description of all supported query parameters.
        final WpCategoryQuery query = WpCategoryQuery.builder()
                                                     .withPostId(100L)
                                                     .build();

        final WpPaginationQuery pagingQuery = new WpPaginationQuery(1, 10);

        final WpPagedResponse<WpCategory> pagedResponse =
                restClient.categories()
                          .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 categories.
        pagedResponse.items()
                     .forEach(category ->
                             System.out.printf(
                                     "[id=%d] [name='%s'] [slug='%s'] [description='%s'] %n",
                                     category.getId(),
                                     category.getName(),
                                     category.getSlug(),
                                     category.getDescription()
                             )
                     );
    }
}