WordPress REST API Client for Java - Samples¶
Creating a Post¶
Create and publish a new WordPress post 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 WpPostCreateUpdateRequest using the fluent builder API.
- Set common post attributes such as the title, content, status, author, slug, excerpt, comment status, and ping status.
- Create the post and receive the resulting WpPost instance returned by the WordPress REST API.
- Access the ID of the newly created post for further processing.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/posts/CreatePost.java
package io.github.evisentin.wordpress.rest.client.samples.code.posts;
import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPost;
import io.github.evisentin.wordpress.rest.client.domain.model.enums.WpOpenClosed;
import io.github.evisentin.wordpress.rest.client.domain.model.requests.WpPostCreateUpdateRequest;
import io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder;
import static io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPostStatus.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 post.
* <p>
* This sample illustrates how to:
* <ul>
* <li>Create a {@link WpRestClient}.</li>
* <li>Build a {@link WpPostCreateUpdateRequest} using the builder API.</li>
* <li>Set common post attributes such as title, content, status, author, slug, excerpt,
* comment status, and ping status.</li>
* <li>Create the post using the WordPress REST API.</li>
* <li>Access the returned {@link WpPost} 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 CreatePost {
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);
WpPostCreateUpdateRequest createRequest =
WpPostCreateUpdateRequest.builder()
.withTitle("The title of my post")
.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 WpPostCreateUpdateRequest Javadoc for other attributes
.build();
final WpPost wpPost = restClient.posts().create(createRequest);
System.out.println("Post created with id=" + wpPost.getId());
}
}
Retrieving a Post¶
Retrieve a single WordPress post by its identifier using the REST API.
This sample demonstrates how to:
- Configure a
WpRestClientusing either Apache HttpClient or OkHttp. - Authenticate using either Basic Authentication or JWT Authentication.
- Retrieve a post by its ID.
- Specify the desired
WpContext(VIEW,EDIT, orEMBED) to control the information returned by the API. - Retrieve a password-protected post by supplying its password.
- Receive the resulting
WpPostinstance returned by the WordPress REST API. - Handle common error scenarios such as unauthorized access, insufficient permissions, or a non-existent post.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/posts/GetPost.java
package io.github.evisentin.wordpress.rest.client.samples.code.posts;
import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPost;
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 post.
* <p>
* This sample illustrates how to:
* <ul>
* <li>Create a {@link WpRestClient}.</li>
* <li>Retrieve a post by its identifier.</li>
* <li>Specify the desired {@link WpContext} for the response.</li>
* <li>Retrieve a password-protected post by supplying its password.</li>
* <li>Access the returned {@link WpPost} instance.</li>
* </ul>
* <p>
* The example shows both retrieving a standard post and accessing a password-protected post.
* The {@link WpContext} controls which fields are included in the response. Public posts are typically retrieved using
* {@code VIEW}, while authenticated users can request {@code EDIT} to obtain additional information.
* <p>
* Depending on the requested post and the current user's permissions, the client may throw exceptions such as:
* <ul>
* <li>{@code WpForbiddenException} if access to the post is denied.</li>
* <li>{@code WpNotFoundException} if the post 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 GetPost {
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 post id=100L exists;
final WpPost wpPost = restClient.posts().get(100L, wpContext);
// Given post id=200L exists and has been created with a password;
final WpPost wpPostWithPassword = restClient.posts().get(100L, wpContext, "my-password");
// PLEASE NOTE: you might get
// - WpForbiddenException
// - WpNotFoundException
// - WpUnauthorizedException
}
}
Deleting a Post¶
Delete a WordPress post using the REST API, either by moving it to the trash or by permanently removing it.
This sample demonstrates how to:
- Configure a
WpRestClientusing either Apache HttpClient or OkHttp. - Authenticate using either Basic Authentication or JWT Authentication.
- Move a post to the WordPress trash, allowing it to be restored later.
- Permanently delete a post and receive a
WpPostDeletionResponse. - Inspect the deletion result and determine whether the post was successfully deleted.
- Access summary information about the deleted post, such as its ID, title, slug, status, and content.
- Handle common error scenarios such as unauthorized access, insufficient permissions, or a non-existent post.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/posts/DeletePost.java
package io.github.evisentin.wordpress.rest.client.samples.code.posts;
import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPost;
import io.github.evisentin.wordpress.rest.client.domain.model.responses.WpPostDeletionResponse;
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 post.
* <p>
* This sample illustrates how to:
* <ul>
* <li>Create a {@link WpRestClient}.</li>
* <li>Move a post to the WordPress trash.</li>
* <li>Permanently delete a post.</li>
* <li>Inspect the returned {@link WpPostDeletionResponse}.</li>
* <li>Access information about the deleted post 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 post to the trash, allowing it to be restored later. Calling {@code delete()} permanently removes the post
* and returns a {@link WpPostDeletionResponse} containing the deletion status together with a summary of the deleted post.
* <p>
* Depending on the requested post 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 post.</li>
* <li>{@code WpNotFoundException} if the post 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 DeletePost {
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 post id=100L exists;
// here the post is marked as ( wpPost.getStatus() == WpPostStatus.TRASH), but still exists, it is possible to recover it.
final WpPost wpPost = restClient.posts().trash(100L);
// here the post is permanently deleted.
final WpPostDeletionResponse deletionResponse = restClient.posts().delete(100L);
final boolean deleted = deletionResponse.isDeleted();// true/false
final WpPostDeletionResponse.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 Post¶
Update an existing WordPress post using the REST API.
This sample demonstrates how to:
- Configure a
WpRestClientusing either Apache HttpClient or OkHttp. - Authenticate using either Basic Authentication or JWT Authentication.
- Build a
WpPostCreateUpdateRequestusing the fluent builder API. - Perform a partial update by specifying only the post attributes that should change.
- Update an existing post by its ID and receive the resulting
WpPostinstance returned by the WordPress REST API. - Change common post 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 post.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/posts/UpdatePost.java
package io.github.evisentin.wordpress.rest.client.samples.code.posts;
import io.github.evisentin.wordpress.rest.client.domain.WpRestClient;
import io.github.evisentin.wordpress.rest.client.domain.model.WpPost;
import io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPostStatus;
import io.github.evisentin.wordpress.rest.client.domain.model.requests.WpPostCreateUpdateRequest;
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 post.
* <p>
* This sample illustrates how to:
* <ul>
* <li>Create a {@link WpRestClient}.</li>
* <li>Build a {@link WpPostCreateUpdateRequest} containing only the fields to be updated.</li>
* <li>Update an existing post using its identifier.</li>
* <li>Access the returned {@link WpPost} instance.</li>
* </ul>
* <p>
* The request performs a partial update: only the fields specified in the {@link WpPostCreateUpdateRequest} are
* modified, while all other post attributes remain unchanged. In this example, the post title is updated and its
* status is changed from {@code DRAFT} to {@code PUBLISH}.
* <p>
* Depending on the requested post 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 post.</li>
* <li>{@code WpNotFoundException} if the post 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 UpdatePost {
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 post id=100L exists and has DRAFT status;
// All the fields not present in the updateRequest shall remain unchanged in the post after the update.
final WpPostCreateUpdateRequest updateRequest =
WpPostCreateUpdateRequest.builder()
.withTitle("My new title")
.withStatus(WpPostStatus.PUBLISH) // it was DRAFT before
.build();
final WpPost updatedPost = restClient.posts().update(100L, updateRequest);
// PLEASE NOTE: you might get
// - WpForbiddenException
// - WpNotFoundException
// - WpUnauthorizedException
}
}
Listing Posts¶
Retrieve a paginated list of WordPress posts using the REST API.
This sample demonstrates how to:
- Configure a
WpRestClientusing either Apache HttpClient or OkHttp. - Authenticate using either Basic Authentication or JWT Authentication.
- Filter posts by status (
Draft,Pending, andPublished). - 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 posts and access common fields such as the ID, title, slug, and status.
samples/src/main/java/io/github/evisentin/wordpress/rest/client/samples/code/posts/ListPosts.java
package io.github.evisentin.wordpress.rest.client.samples.code.posts;
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.WpPost;
import io.github.evisentin.wordpress.rest.client.domain.model.query.WpPaginationQuery;
import io.github.evisentin.wordpress.rest.client.domain.model.query.WpPostQuery;
import io.github.evisentin.wordpress.rest.client.samples.code.SampleClientBuilder;
import static io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPostStatus.DRAFT;
import static io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPostStatus.PENDING;
import static io.github.evisentin.wordpress.rest.client.domain.model.enums.WpPostStatus.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 posts.
* <p>
* This sample illustrates how to:
* <ul>
* <li>Create a {@link WpRestClient}.</li>
* <li>Filter posts using a {@link WpPostQuery}.</li>
* <li>Request a post of results using {@link WpPaginationQuery}.</li>
* <li>Access pagination metadata.</li>
* <li>Iterate over the returned {@link WpPost} instances.</li>
* </ul>
* <p>
* Before running this sample, configure the connection details in {@link SampleClientBuilder} so they match your
* WordPress installation.
*/
public class ListPosts {
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);
// WpPostQuery provides many attributes for filtering posts. This example filters by post status only.
// Refer to the class Javadoc for a complete description of all supported query parameters.
final WpPostQuery query = WpPostQuery.builder()
.withStatus(DRAFT)
.withStatus(PUBLISH)
.withStatus(PENDING)
.build();
final WpPaginationQuery pagingQuery = new WpPaginationQuery(1, 10);
final WpPagedResponse<WpPost> pagedResponse =
restClient.posts()
.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 posts.
pagedResponse.items()
.forEach(post ->
System.out.printf(
"[id=%d] [title='%s'] [slug='%s'] [status='%s'] %n",
post.getId(),
post.getTitle().getRendered(),
post.getSlug(),
post.getStatus()
)
);
}
}