Skip to content

WordPress REST API Client for Java - Samples

Creating a Tag

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

import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpTag;
import io.github.evisentin.wordpress.rest.client.domain.model.requests.WpTagCreateUpdateRequest;
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 tag.
 * <p>
 * This sample illustrates how to:
 * <ul>
 *     <li>Create a {@link WpRestClient}.</li>
 *     <li>Build a {@link WpTagCreateUpdateRequest} using the builder API.</li>
 *     <li>Set common tag attributes such as the name, slug, description, and parent tag.</li>
 *     <li>Create the tag using the WordPress REST API.</li>
 *     <li>Access the returned {@link WpTag} 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 CreateTag {
    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);

        WpTagCreateUpdateRequest createRequest =
                WpTagCreateUpdateRequest.builder()
                                        .withName("My Tag")
                                        .withSlug("my-tag") // if not provided, it is computed by WordPress
                                        .withDescription("The description of my tag")
                                        .build();

        final WpTag wpTag = restClient.tags().create(createRequest);

        System.out.println("Tag created with id=" + wpTag.getId());
    }
}

Retrieving a Tag

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

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

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

Deleting a Tag

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

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

        final WpTagDeletionResponse deletionResponse = restClient.tags().delete(100L);

        final boolean deleted = deletionResponse.isDeleted(); // true/false
        final WpTagDeletionResponse.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 Tag

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

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

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

        final WpTag updatedTag = restClient.tags().update(100L, updateRequest);

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

Listing Tags

Retrieve a paginated list of WordPress tags 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 tags 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 tags and access common fields such as the ID, name, slug, and description.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/tags/ListTags.java
package io.github.evisentin.wordpress.rest.client.samples.code.tags;

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

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

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

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