Coder Social home page Coder Social logo

wp-api-v2-client-java's Introduction

LOOKING FOR A MAINTAINER

Codeship Status for Afrozaar/wp-api-v2-client-java

WP-API v2 Java Client

A Java client to version 2 of the WP REST API, recently merged into WordPress Core

(Currently coding against WordPress 4.8.x)

WordPress Supported Versions

The current 4.8 version supports WordPress 4.6-4.8.

See

Current Development Requirements

  • WordPress 4.8.0+ installation
  • JSON Basic Authentication (0.1 currently used)

Implemented

  • Posts CRUD
  • Post Meta CRUD
  • Terms CRUD
  • Taxonomy CRUD
  • Post Terms CRUD
  • Pages CRUD
  • Users

Work In Progress

...

Not Yet Implemented

  • Post Revisions
  • Post Types
  • Post Statuses
  • Comments

Basic Usage

Instantiating and using a new client

String baseUrl = "http://myhost";
String username = "myUsename";
String password = "myPassword";
boolean debug = false;

final Wordpress client = ClientFactory.fromConfig(ClientConfig.of(baseUrl, username, password, debug));

Creating a new post

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);

Searching Posts

Search Posts not having a particular Meta Key

Sample Code

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());                

Equivalent Curl/httpie Request

$ http --auth 'username:password' http://myhost/wp-json/wp/v2/posts?filter[meta_key]=baobab_indexed&filter[meta_compare]=NOT%20EXISTS

Search types

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());

Available Filters

More Usage Examples

Advanced/Restricted Filtering

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' );

Controlling HTTP Connection behavior

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();

TODO

  • Add support for authentication providers such as OAuth. (Currently only basic authentication is used)

Testing

Live Testing

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.

Configuration

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.

Maven

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>

wp-api-v2-client-java's People

Contributors

clintonbosch avatar freddieod avatar johanmynhardt avatar manikmagar avatar michaelwiles avatar simonit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wp-api-v2-client-java's Issues

RestClientException when trying to create a post

Hey there,

I am getting a RestClientException:
Exception in thread "main" org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.afrozaar.wordpress.wpapi.v2.model.Post] and content type [text/html;charset=UTF-8]

Is this repository still supported with Wordpress 5.x?

Production ready?

Hi, not really an issue but couldn't find any other place to write. I really liked these API. I had started creating my own rest client for wp-api but later discovered this and thought why to reinvent the wheel :). Thanks for creating these clean and neat java client for WP API.

I am planning to use these API in my J2EE web app which will talk to Wordpress CMS with these. I wanted to thoughts on how stable and production-ready these api's are? I presume these are open source and free to use/modify :). I know these are all new (and so does WP REST API).

Thanks.

Improve batch handling of tags

For example, when creating multiple tags on a post, it might be better to create the tags and then set them in a batch instead of updating the post each time a tag is added.

Can this be used to add podcast episodes to PowerPress?

https://forum.blubrry.com/index.php?topic=3466.0
I read here that you need to add information to custom fields in order to do this

`$enclosure_value = $row['url'];
$enclosure_value .= "\n";
$enclosure_value .= $row['size'];
$enclosure_value .= "\n";
$enclosure_value .= $type;

    $content['title'] = $title;
    $content['description'] = $body;
    $content['categories'] = array("Meetings");
    /*Pass custom fields*/
    $content['custom_fields'] = array(
        array( 'key' => 'enclosure', 'value' => $enclosure_value )
        );`

Can this be done using this java library?
Thank you

Add capability to make calls without requiring pretty permalinks.

Doing this would allow the client to make calls using the http[s]://basehost/?rest_route=/wp/v2/* structure.

It is found that some sites have difficulty with /wp-json/wp/v2/* pretty permalinks or hiding it from discovery (so the rest calls are available, just not visible for inspection, or when making a call to it, the call would just fail).

403 Forbidden error when connecting from local to remote WP

I develop my web application in local laptop and my wordpress is deployed on remote VPS. I use this API to get custom post data from wordpress. All was working good in local but suddenly I started getting 403 Forbidden error for every API call eg. getUsers().

There is no change in user/password/roles. API calls using postman with same user/password works. More surprisingly when I build the WAR from local and deployed on the VPS that hosts wordpress then there everything seems to work normally. I even created another simple maven java project in local, added this wp-api-v2-client-java dependency. Then created a simple JUnit test to getUsers() but it failed.

Also if I use Postman with same id/password to call same endpoint from my local to remote VPS, it works.

I am not sure what is going on. I have wp api beta 13 with wordpress 4.5, can that be an issue? I updated wp api to beta 13 as soon as it was out, I guessed it was working after that too.

Latest version (4.14) on start ends with exception

Hello, dear developer!
I have builded jar from source code with maven.
Steps to reproduce the problem:

  • download the project
  • navigate via terminal (cd {path})
  • mvn compile
  • mvn package
    Then I get jar file which I included inside project via Gradle.
    When I run the project get the exception of Spring Framework...
    Caused by: java.lang.ClassNotFoundException: org.springframework.util.MultiValueMap
    How I can fix it or may be you can add the latest package to mvnrepository? The latest package version on mvnrepository is 4.8.3
    P.S. Here is the compiled jar for 4.14 version -
    https://yadi.sk/d/uAxj1D2JScHh8A
    Thanks in advance!)

setCategoryIds

Hi,

I'm trying to assign categories to posts but is always assigned to Uncategorized.

Post post = new Post();
post.setTitle(aTitle().withRendered(title).build());
post.setExcerpt(anExcerpt().withRendered(excerpt).build());
post.setContent(aContent().withRendered(content).build());

List list = new ArrayList();
list.add(155L);
post.setCategoryIds(list);
client.createPost(post, PostStatus.publish);

Is there something wrong with my code?

Thank you

Calling createMeta() causes HTTP/400 (Bad Request) in custom project.

When using this library in a custom project which already has other jackson-databind dependencies,
the MappingJackson2XmlHttpMessageConverter is also added, and it just so happens that it precedes MappingJackson2HttpMessageConverter.

When the body being sent through RestTemplate is a Map, it for some reason gets translated to XML, instead of JSON.

getPost(id, "embed") does not work

Hello,

I have a problem with the get of a post with the context "embed".

The additionalProperties attribute is empty when I use this context, however it is not empty when I use a search instead of getPost (id)

I need to have detail of author, tags and categories with one call to api wp

Do you have an idea ?

Thank you

User Management Exception handling is not closed for extension

The exception handling in the User Context (and maybe in other contexts) is a little too specific.

The exceptions need to be a little more generic. i.e. not UserAlreadyExistsException but rather WpApiException that has a code that indicates the error is "user already exists"...

Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token

Wrapped by: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
 at [Source: java.io.PushbackInputStream@4ae32ea0; line: 1, column: 327] (through reference chain: com.afrozaar.wordpress.wpapi.v2.model.User["capabilities"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token
 at [Source: java.io.PushbackInputStream@4ae32ea0; line: 1, column: 327] (through reference chain: com.afrozaar.wordpress.wpapi.v2.model.User["capabilities"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:225) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:209) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:95) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:835) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:819) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:599) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:572) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:534) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
    at com.afrozaar.wordpress.wpapi.v2.Client.doExchange0(Client.java:734) ~[na:na]
    at com.afrozaar.wordpress.wpapi.v2.Client.doExchange0(Client.java:740) ~[na:na]
    at com.afrozaar.wordpress.wpapi.v2.Client.doExchange1(Client.java:753) ~[na:na]
    at com.afrozaar.wordpress.wpapi.v2.Client.doExchange1(Client.java:744) ~[na:na]
    at com.afrozaar.wordpress.wpapi.v2.Client.getUser(Client.java:625) ~[na:na]

Error: No content to map due to end-of-input

Hi
I am able to connect and retrieve categories.
I am getting an error when trying to make a post.

final Post post = aPost().withTitle(aTitle().withRendered(expectedTitle).build()) .withExcerpt(anExcerpt().withRendered(expectedExcerpt).build()) .withContent(aContent().withRendered(expectedContent).build()) .withCategories(catogeryList) .build();

java.lang.RuntimeException: Can not create ParsedRestException.
Done
at com.afrozaar.wordpress.wpapi.v2.exception.ParsedRestException.of(ParsedRestException.java:105)
at com.afrozaar.wordpress.wpapi.v2.exception.PostCreateException.(PostCreateException.java:8)
at com.afrozaar.wordpress.wpapi.v2.Client.createPost(Client.java:156)
at com.afrozaar.wordpress.wpapi.v2.Client.createPost(Client.java:162)
at com.analyst.orchestrator.WebPublisher.main(WebPublisher.java:81)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
at [Source: [B@751e664e; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3781)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3721)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2819)
at com.afrozaar.wordpress.wpapi.v2.exception.ParsedRestException.of(ParsedRestException.java:98)

Searching for posts by status draft

Hi,

I tried searching for posts. I need to find those having a post with a certain title with the "draft" status.

SearchRequest<Post> sr = 
            SearchRequest.Builder.aSearchRequest(Post.class)
            .withUri(Request.POSTS)
            .withFilter("title",episode.getTitle())
            .withFilter("status","draft")
            .build();
    PagedResponse<Post> postsAlreadyThere = client.search(sr);`

This returns all posts with "published" status.
I also tried with post_status and post_title for filter as well, but no change.
I tried installing a JSON filter plugin in my wordpress https://github.com/WP-API/rest-filter , but unfortunatelly nothing seems to work

Am I doing somethingwrong or is this a bug?

Certificate error when https enabled wordpress is called.

I was trying to get list of posts from https enabled wordpress but RestTemplate threw an exception for invalid certificate. I looked into the code but did not see any support for https.

I have forked and modified Wordpress initialization process to optionally provide ClientHttpRequestFactory that handles TLS connections and now can call HTTPS endpoints too.

Is there any other way to handle SSL with current code?

While Creating / Updating post "slug" value gets ignored.

Hello Team.

While creating / updating a post, value passed for Slug is getting ignored.

Post post = PostBuilder.aPost()
.withTitle(TitleBuilder.aTitle().withRendered("ABCDTitleUpdate124").withRaw("ABCDTitleUpdate124").build())
.withExcerpt(ExcerptBuilder.anExcerpt().withRendered("ABCDTitle124Excerpt").build())
.withContent(ContentBuilder.aContent().withRendered("ABCDTitle124Content").build())
// This string will get ignored completely while creating / updating post.
.withSlug("sampleslug")
.build();

Regards,
Sumit

Some questions about WP API V2 Client

Hello!
First of all, thank you so much for this java client.
I have some questions and because of the lack of documentation I would like to clarify them with you. Hope you take some time with me. Thank you in advance!
Is client version 4.13.x working?
I have builded jar in Intellij IDEA ( empty jar or jar from modules with dependencies) and try the snippet below I get another exception:

16:38:05.860 [main] ERROR c.a.w.wpapi.v2.util.MavenProperties - Error loading properties 
java.lang.NullPointerException: null
	at java.util.Properties$LineReader.readLine(Properties.java:434) ~[na:1.8.0_191]
	at java.util.Properties.load0(Properties.java:353) ~[na:1.8.0_191]
	at java.util.Properties.load(Properties.java:341) ~[na:1.8.0_191]
	at com.afrozaar.wordpress.wpapi.v2.util.MavenProperties.getProperties(MavenProperties.java:19) ~[wp-api-v2-client-java.jar:4.1.7.RELEASE]
	at com.afrozaar.wordpress.wpapi.v2.Client.<init>(Client.java:90) [wp-api-v2-client-java.jar:4.1.7.RELEASE]
	at com.afrozaar.wordpress.wpapi.v2.Client.<init>(Client.java:95) [wp-api-v2-client-java.jar:4.1.7.RELEASE]
	at com.afrozaar.wordpress.wpapi.v2.config.ClientFactory.fromConfig(ClientFactory.java:12) [wp-api-v2-client-java.jar:4.1.7.RELEASE]
	at testt.test.main(test.java:22) [classes/:na]
16:38:06.604 [main] DEBUG c.afrozaar.wordpress.wpapi.v2.Client - Request Entity: <POST https://md7.info?rest_route=/wp/v2/posts,{author=[null], content=test, title=test, status=publish},{User-Agent=[null/null], Authorization=[Basic YWRtaW46Z2xvYmFsbmV0d29yazI0], Content-Type=[application/json]}>
com.afrozaar.wordpress.wpapi.v2.exception.PostCreateException: 400 Bad Request parameter: author
	at com.afrozaar.wordpress.wpapi.v2.Client.createPost(Client.java:146)
	at com.afrozaar.wordpress.wpapi.v2.Client.createPost(Client.java:152)
	at testt.test.main(test.java:35)
Caused by: org.springframework.web.client.HttpClientErrorException: 400 Bad Request
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
	at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:614)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:570)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:545)
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:507)
	at com.afrozaar.wordpress.wpapi.v2.Client.doExchange0(Client.java:1007)
	at com.afrozaar.wordpress.wpapi.v2.Client.doExchange0(Client.java:1013)
	at com.afrozaar.wordpress.wpapi.v2.Client.doExchange1(Client.java:1034)
	at com.afrozaar.wordpress.wpapi.v2.Client.createPost(Client.java:144)
	... 2 more

Snippet which I used to test the client:

public class test {
  public static void main(String[] args) {
    String url = "https://example.com";
    String login = "admin";
    String password = "12345";
    final Wordpress client = ClientFactory.fromConfig(ClientConfig.of(
            url, login, password, false, true
    ));
    String articleTitle = "test";
    String articleContent = "test";
    final Post post = PostBuilder.aPost()
            .withTitle(TitleBuilder.aTitle().withRendered(articleTitle).build())
            .withContent(ContentBuilder.aContent().withRendered(articleContent).build())
            .build();
    try {
      final Post createdPost = client.createPost(post, PostStatus.publish);
    } catch (PostCreateException e) {
      e.printStackTrace();
    }

  }
}

P.S. When I use this snippet with the client version 4.8.3 (from mvnrepository) It works well. Link

Links to builded jar:
https://send.firefox.com/download/6b87ae513fe90145/#4A71Xr6QLSwcQunFT-qTpw

P.P.S. And what about JWT authentication?
Thanks again!

Allow specifying request context (view | edit | embed) when requesting Media

The methods getMedia(Long id) and getPostMedias(Long postId) (from Medias) use request context mode EDIT.
Please allow specifying the context mode for both methods. (e.g. if I just want to fetch a Media for an ID, the usage of context=edit in getMedia(id) will cause the request to fail, because the Wordpress server only allows context=view).

401 unauthorized error

I am trying to play around with the API methods to create and get users. But I keep getting 401 Unauthorized error. I tried with the admin ID and password but I am not sure why I get 401 unauthorized error. Below is my code and request and response log. I have replaced my actual user id and pwd with *** for security purposes.. Pls advise.

09:49:13.490 [main] DEBUG c.afrozaar.wordpress.wpapi.v2.Client - Request Entity: <GET https://cs.genoo.com?rest_route=/wp/v2/users&context=view,{Authorization=[Basic R24zc2lQMDpGRjR4QFZkS3otLTJIWWlzWkM=], User-Agent=[wp-api-v2-client-java/4.8.1]}>
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized

public class WordPressAPI {

public static void main (String args[]) {
	com.afrozaar.wordpress.wpapi.v2.Wordpress wordpress = getWordpressClient();
	System.out.println(wordpress);
	
	User user = new User();
	List<User> users = new ArrayList<User>();
	user.setEmail("[email protected]");
	user.setName("Name");
	/*try {
	  user = wordpress.createUser(user, "[email protected]", 
			  "test");
	 users = wordpress.getUsers();
	 System.out.println("Users ==" + users);
	} catch (UsernameAlreadyExistsException e) {
	  e.printStackTrace();
	} catch (UserEmailAlreadyExistsException e) {
	  e.printStackTrace();
	} catch (WpApiParsedException e) {
		e.printStackTrace();
	}*/
	
	 users = wordpress.getUsers();
	 System.out.println("Users ==" + users);
	 
	Term term = new Term();
	term.setName("Test Hunter");
	term.setSlug("Delete this entry");
	Term cat = wordpress.createCategory(term);
	System.out.println(cat);
}

public static com.afrozaar.wordpress.wpapi.v2.Wordpress getWordpressClient() {
    String baseUrl = "https://cs.genoo.com";
    String username = "*****";
    String password = "*****";
    return ClientFactory
      .fromConfig(ClientConfig.of(baseUrl, username, password,
          false,
          true));
}

Can not create ParsedRestException

Hello)
I am trying to write a first application in Spring to publish articles on the Wordpress website. I get an exception. I use WP REST API Client 4.8.3 and WordPress version 4.9.8 (clean installation). Where am I mistaken or not support this WordPress version? Thanks in advance!

public class WpTest {
    public static void main(String[] args) {

        String baseUrl = "http://example.com";
        String username = "customUser";
        String password = "customPassword";
        boolean usePermalinkEndpoint = false;
        boolean debug = true;

        final Wordpress client = ClientFactory.fromConfig(ClientConfig.of(baseUrl, username, password, usePermalinkEndpoint, debug));

        String expectedTitle = "Demo Title";
        String expectedExcerpt = "Demo Excerpt";
        String expectedContent = "Demo Content";

        final Post post = PostBuilder.aPost()
                .withTitle(TitleBuilder.aTitle().withRendered(expectedTitle).build())
                .build();

        try {
            final Post createdPost = client.createPost(post, PostStatus.publish);
        } catch (PostCreateException e) {
            e.printStackTrace();
        } 
    }
}

Exception:

Exception in thread "main" java.lang.RuntimeException: Can not create ParsedRestException.
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input at [Source: (byte[])""; line: 1, column: 0]

Be able to parse rest exceptions from multisites.

@MaSeKind discovered that there is a difference between 4.7.2 and versions before it:

OLD:

{
 "code": "user_email",
 "message": "Sorry, that email address is already used!",
 "data": null
}

NEW:

{
 "code": "rest_invalid_param",
 "message": "Invalid user parameter(s).",
 "data": {
   "status": 400
 },
 "additional_errors": [
   {
     "code": "user_name",
     "message": "Sorry, that username already exists!",
     "data": null
   },
   {
     "code": "user_email",
     "message": "Sorry, that email address is already used!",
     "data": null
   }
 ]
}

However, I could only pin it down to multisite-related changes from https://core.trac.wordpress.org/changeset/39219

401 : rest_cannot_create

I am using this for creating post in wordpress but I am getting the below mentioned error for this. I got this in the wordpress REST API Logs.

I am able to read the post correctly but getting this only in creating post

"data": {
"code": "rest_cannot_create",
"message": "Sorry, you are not allowed to create posts as this user.",
"data": {
"status": 401
}
}

Can not parse non-standard boolean values ('yes','no','1','0)

TL;DR: The issue is bad/inconsistent data.

In Depth
The WP-API and our Java Client agrees on the data structure being used to transmit data, which is JSON. The user capabilities is a map of {string: boolean} values, and in JSON it looks something like the following:

{
  "capabilities": {
    "foo": true,
    "bar": false
  }
}

but we received something like:

{
  "capabilities": {
    "foo": "1",
    "bar": false
  }
}

Which can not be deserialized properly and causes the stack trace included in the description.
By digging around in a local wordpress installation's database structure it is found that for complex structures, the entire structure is serialized using PHP's string serialize(mixed $value) function.

wp_usermeta
In the wp_usermeta table an entry with the key wp_capabilities is found containing such a serialized value.
Standard format for admin user's wp_capabilities value

mysql> select * from wp_usermeta where meta_key = 'wp_capabilities' and user_id = 1;
+----------+---------+-----------------+---------------------------------+
| umeta_id | user_id | meta_key        | meta_value                      |
+----------+---------+-----------------+---------------------------------+
|       10 |       1 | wp_capabilities | a:1:{s:13:"administrator";b:1;} |
+----------+---------+-----------------+---------------------------------+

The structure a:1:{s:13:"administrator";b:1;} translate to an array of length 1 containing a string-key (of 13 characters, administrator) and a boolean-value, 1, which denotes true.
Changing this value to a:1:{s:13:"administrator";s:1:"1";} (array of length 1 containing a string-key of 13 characters, administrator and a string-value of 1 character with value 1)
and making a call to the endpoint exerts the breaking behaviour experienced.
So it appears that someone modified this value, or it was incorrectly modified by a plugin (this is hard to do by hand and getting it wrong will brick some usability if not the wordpress site).

Solution

The appropriate solution would be to fix this so that the intended data is actually flowing through WordPress.

UTF8 characters - Latin Diacritics are not rendering properly

Hi,

I checked the output of the REST API call from the browser, it is showing Latin Diacritics properly, however, the string returned from com.afrozaar.wordpress.wpapi.v2.model.Post.getContent().getRendered() contains an invalid string with the special characters appearing as ?.
It should be an easy fix for the author, I believe somewhere the conversion is not happening properly. I will try to fix it and submit a PR but please do check.

Update
I was able to fix this. You need to slightly edit the file

com.afrozaar.wordpress.wpapi.v2.Client.java:127
Before

        restTemplate = new RestTemplate(messageConverters);

After

import java.nio.charset.StandardCharsets;
....
        restTemplate = new RestTemplate(messageConverters);
        restTemplate.getMessageConverters()
            .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

It is a very simple change, I have never submitted a PR actually, may be the authors can fix this on their own. If a PR is required let me know, I will submit one. For now, this solves my problem.

Thanks

Internal Server Error 500 status code when createUser with existing username is called

When I call createUser() method with existing username then instead of getting user already exists error, I get 500 Internal Server error.

I tried calling WP API for endpoint using Postman tool for same user id and there I am getting proper error message response as -
{
"code": "existing_user_login",
"message": "Sorry, that username already exists!",
"data": null
}

Need to check more on this.

Expose data structures available in Wordpress 4.7

There are several structural changes that are now available in 4.7, like renderable fields where the field has 2 children with the fields raw and rendered, as well as when a delete request is made, it will respond with a new field indicating whether it was deleted or not, and the previous value of the object.
There is a new meta field that is also available on the Term entity.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.