首页 > 解决方案 > WP_remote_post how to add filters to JSON API call

问题描述

I am trying to integrate an API into my Wordpress plugin. The following PHP code successfully connects to the API and retrieves a list of Estates (the API is from a real-estate software):

$url = 'https://api.whise.eu/v1/estates/list';

$body = array(
    'Filter' => array( 'languageId' => 'nl-BE'),
);

$args = array(
    'headers' => array( 'Authorization' => 'Bearer ' . $token),
    'body' => json_decode($body)
);

$response = wp_remote_post($url,$args);

As per the documentation (http://api.whise.eu/WebsiteDesigner.html#operation/Estates_GetEstates) it is possible to filter the results, but I haven't been able to get this to work. I don't have much experience with APIs and JSON, so I might be missing something here.

The code above still retrieves the data in English, even though I added the language filter as explained in the docs. When I replace 'body' => json_decode($body) with 'body' => $body, I get the following response:

{"Message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}

Thanks!

标签: jsonwordpressapi

解决方案


Just so that this question doesn't go unanswered:

  • You need to add the Content-Type header and set it to application/json. This is so the endpoint can interpret your data as a JSON string.
  • You also need to change 'body' => json_decode($body) to 'body' => json_encode($body) as you want to convert your $body array into a JSON string (see json_decode() vs json_encode()).

This is how your code should look now:

$url = 'https://api.whise.eu/v1/estates/list';

$body = array(
    'Filter' => array( 'languageId' => 'nl-BE'),
);

$args = array(
    'headers' => array(
        'Authorization' => 'Bearer ' . $token,
        'Content-Type' => 'application/json'
    ),
    'body' => json_encode($body)
);

$response = wp_remote_post($url,$args);

推荐阅读