A Java client to version 2 of the WP REST API, recently merged into WordPress Core
(Currently coding against WordPress 4.8.x)
The current 4.8 version supports WordPress 4.6-4.8.
See
...
String baseUrl = "http://myhost";
String username = "myUsename";
String password = "myPassword";
boolean debug = false;
final Wordpress client = ClientFactory.fromConfig(ClientConfig.of(baseUrl, username, password, debug));
final Post post = PostBuilder.aPost()
.withTitle(TitleBuilder.aTitle().withRendered(expectedTitle).build())
.withExcerpt(ExcerptBuilder.anExcerpt().withRendered(expectedExcerpt).build())
.withContent(ContentBuilder.aContent().withRendered(expectedContent).build())
.build();
final Post createdPost = client.createPost(post, PostStatus.publish);
final PagedResponse<Post> response = client.search(SearchRequest.Builder.aSearchRequest(Post.class)
.withUri(Request.POSTS)
.withParam("filter[meta_key]", "baobab_indexed")
.withParam("filter[meta_compare]", "NOT EXISTS") //RestTemplate takes care of escaping values ('space' -> '%20')
.build());
$ http --auth 'username:password' http://myhost/wp-json/wp/v2/posts?filter[meta_key]=baobab_indexed&filter[meta_compare]=NOT%20EXISTS
The client is flexible enough to build search requests of a particular type, if that type supports filtering.
final PagedResponse<Media> tagResults = client.search(SearchRequest.Builder.aSearchRequest(Media.class)
.withUri("/media")
.withParam("filter[s]", "searchTerm")
.build());
/src/test/java/com/afrozaar/wordpress/wpapi/v2/ClientLiveTest.java
which has all the tests for a live installation and thus has examples of how to use the client.For advanced filtering in a particular use case, it is required to search for posts not having a particular custom field. In order to search for such posts, the standard filter keys are not sufficient, and needs to be enabled by allowing more keys.
Do note that the effect of this change is only visible when an authenticated call is made, as per the WP-API documentation.
A snippet containing the keys that you wish to use needs to be added to either your theme's functions.php
file, or WP-API's plugin.php
:
function my_allow_meta_query( $valid_vars ) {
$valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value', 'meta_compare' ) );
return $valid_vars;
}
add_filter( 'rest_query_vars', 'my_allow_meta_query' );
If needed, org.springframework.http.client.ClientHttpRequestFactory
can be provided to control the HTTP connection behavior. Below example shows how to disable SSL verification when invoking https wordpress endpoints.
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
boolean debug = false;
final Wordpress wordpress = ClientFactory.builder(ClientConfig.of(httpBaseURL, username, password, debug))
.withRequestFactory(requestFactory)
.build();
These tests are intended to run against a live WordPress installation.
For convenience, a wordpress docker has been created. This docker has a pre-installed-and-set-up wordpress instance, with the latest (beta9) version of rest-api and JSON Basic Auth plugins enabled. Configuration has already been included in the test configuration directory.
To make use of this docker, you can do the following:
docker run -d --name wp_build_test -p 80:80 afrozaar/wordpress:latest
More configuration is required (adding an entry to your hosts file), so see Afrozaar/docker-wordpress on GitHub.
To run against your local wordpress installation, it is required to have a YAML configuration file
available at: ${project}/src/test/resources/config/${hostname}-test.yaml
with the following structure:
wordpress:
username: "myUsername"
password: "myPassword"
baseUrl: "http://myhost"
usePermalinkEndpoint: false
debug: "true"
This configuration must not be included in version control. *.yaml
is already included in the .gitignore
file.
Please ensure that you do not commit hard-coded environment information.
Latest snapshot is available from our public maven repository at
Release versions should also be available on public maven repositories:
<dependency>
<groupId>com.afrozaar.wordpress</groupId>
<artifactId>wp-api-v2-client-java</artifactId>
<version>4.8.1</version>
</dependency>