Custom wordpress REST API to accept JSON formatted input - wordpress

I'm writing a wordpress REST API using the WP REST v2. Is there a way we can process the incoming JSON parameters (instead of query params) within the callback function, which we define in the register_rest_route function?
eg:
function wpplugin_register_routes() {
register_rest_route( 'testapi/v1', 'users', array(
'methods' => 'POST',
'callback' => 'wpplugin_process_json_params',
) );
}
function wpplugin_process_json_params( WP_REST_Request $request ) {
// Process the $request which should be a JSON string
}

Found the solution for this. WP_REST_Request object contains the JSON parameters so can retrieve it using $request['parameter_name'] same as the GET / POST parameters.

Related

how to make custom wordpress rest api and get posts results with arabic language parameter

I create API route for search
I try to get a parameter search in Arabic containing about (two words)
but it didn't work, I try almost of video, and not working
try Unicode and encode JSON also
Does anybody have a solution for it?
my API route
add_action('rest_api_init', function() {
register_rest_route( 'wm/v1', '/search/(?p<request>.+)', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'wm_search_post',
) );
enter code here
and the Endpoint callback function
function wm_search_post(WP_REST_Request $request){
$req=JSON_encode($request['request']);
return $req;
// here I try to test the results but get rest_no_route
//404 >>> but it is work if I remove parameter
}}
Your regex expression is not correct and also some of your closing braces missing. Let's see the below code, it's working on my end.
add_action('rest_api_init', function() {
register_rest_route( 'wm/v1', '/search/(?P<request>\w+)/', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'wm_search_post',
));
});
function wm_search_post(WP_REST_Request $request) {
$req= $request['request'];
return rest_ensure_response($req);
}
You can get a response http://localhost/elementskit/wp-json/wm/v1/search/<pass_string_here>
Hope that will work!

Respond to custom URL in wordpress plugin

So, I'm trying to write a wordpress plugin which acts like an API and responds to a specific HTTP request. I cache some data in my plugin and I would like to fetch the data in the other side using AJAX or sth.
What actions or filters should I use? I've tried using request filter but couldn't figure out how it works.
Use the WP REST API for this: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/
Below is a simple example of how to add a custom route and how to handle the request.
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/my-custom-route/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
function my_awesome_func( WP_REST_Request $request ) {
// You can access parameters via direct array access on the object:
$param = $request['some_param'];
// Or via the helper method:
$param = $request->get_param( 'some_param' );
// You can get the combined, merged set of parameters:
$parameters = $request->get_params();
// The individual sets of parameters are also available, if needed:
$parameters = $request->get_url_params();
$parameters = $request->get_query_params();
$parameters = $request->get_body_params();
$parameters = $request->get_json_params();
$parameters = $request->get_default_params();
// Uploads aren't merged in, but can be accessed separately:
$parameters = $request->get_file_params();
}

Wordpress REST response shows taxonomy categories only with ID's

I'm using WP as a headless CMS with ACF en ACF-2-REST plugins. I've added categories to a post-type and when I make a GET call, it shows me all the information of a particular post including the categories, but only the ID's. If I want to match it, I have to do another call to Categories to get the information of that categories (name, parent etc).
How can I show that information instead of just the ID in a post call?
How the JSON looks now at the /activities call:
{
"id":111,
"date":"2020-01-18T15:39:27",
"date_gmt":"2020-01-18T15:39:27",
"guid":{"rendered":"https:\/\/url.be\/?post_type=activities&p=111"},
"modified":"2020-01-18T15:39:27",
"modified_gmt":"2020-01-18T15:39:27",
"slug":"walking-on-wood",
"status":"publish",
"type":"activities",
"link":"https:\/\/url.be\/activities\/walking-on-wood\/",
"title":{"rendered":"Walking on wood"},
"template":"",
"categories":[14,25,13,2,18,21,6,24],
"acf":{...}
}
What I want to show in the "categories" instead of just the numbers (from the categories call)
{
"id":3,
"count":1,
"description":"",
"link":"https:\/\/url.be\/category\/duration\/lower-than-30-min\/",
"name":"< 30 min.",
"slug":"lower-than-30-min",
"taxonomy":"category",
"parent":2,"meta":[],
"acf":[],
"_links":{"self":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories\/3"}],
"collection":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories"}],
"about":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/taxonomies\/category"}],
"up":[{"embeddable":true,"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories\/2"}],
"wp:post_type":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/posts?categories=3"},{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/activities?categories=3"}],
"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}
}
Can't find any solution on the internet how I could manipulate the structure of that JSON with a custom function, would appreciate it a lot if someone point me to the right direction. Thanks!
As discussed in the comments section, a solution to this question is to use a custom endpoint method for the WP REST API and perform extra queries in there to get the data you need. This way, you can do all the data manipulation to get the perfect response, resulting in one REST call.
As taken from the official developer docs
Define an endpoint method and add some extra data
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func', //note that this is the method it will fire
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
) );
/**
* Grab latest post by an author along with its category!
*
* #param array $data Options for the function.
* #return array Post,
*/
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if(!empty($posts)) {
//Example of appending extra data
foreach($posts as $post) {
$category = wp_get_post_terms($post->ID, 'category');
$post['category'] = $category;
}
return $posts;
} else {
return new WP_Error( 'no_author', 'Invalid author', array( 'status' => 404 ) );
}
}

WooCoommerce custom endpoint - Enable auth protection

I have defined the following custom endpoint for woocommerce:
add_action( 'rest_api_init', 'custom_endpoint' );
function custom_endpoint() {
register_rest_route( 'wc/v3', 'my_custom_endpoint', array(
'methods' => 'GET',
'callback' => 'return_value',
) );
}
function return_value() {
return "this is my custom endpoint!";
}
However, this endpoint is also accessible if I'm not authenticated using the ck and cs.
How can I protect it the same way all other, default endpoints of the WooCommerce API are protected? (I would prefer not needing another auth plugin for this to work, but to access it with the standard WooCommerce auth keys instead).
Thanks!
Hello use permission_callback with JWT Authentication for WP REST API plugin so it will work fine.
Steps :
1) Install JWT Authentication for WP REST API plugin
2) Set permission_callback
Below code will work well after JWT Authentication for WP REST API plugin installation
add_action('rest_api_init', 'custom_endpoint');
function custom_endpoint(){
register_rest_route('wc/v3', 'my_custom_endpoint', array(
'methods' => 'GET',
'callback' => 'return_value',
'permission_callback' => function($request){
return is_user_logged_in();
}
));
}
function return_value(){
return "this is my custom endpoint!";
}
for more information please check JWT Authentication for WP REST API documentation.
Checked and works well.
Cookie authentication is the standard authentication method included with WordPress. When you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme developers need only to have a logged-in user.
As an example, this is how the built-in Javascript client creates the nonce:
<?php
wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );
This is then used in the base model:
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
if (beforeSend) {
return beforeSend.apply(this, arguments);
}
};
Here is an example of editing the title of a post, using jQuery AJAX:
$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
Note that you do not need to verify that the nonce is valid inside your custom end point. This is automatically done for you in
rest_cookie_check_errors()
Woocommerce API
https://woocommerce.github.io/woocommerce-rest-api-docs/?php#authentication-over-https
While cookie authentication is the only authentication mechanism
available natively within WordPress, plugins may be added to support
alternative modes of authentication that will work from remote
applications.
As Per Official Document : https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins

WordPress REST API not enabled on new account

Based on a quick research, WordPress REST API should be enabled after v4.7 (https://v2.wp-api.org/), however, I cannot access the REST API for my existing or new user by simply appending {name}.wordpress.com/wp-json, ie. https://steventsaotest.wordpress.com/wp-json does not return the expected JSON. Whereas sites like http://www.tribunemedia.com/wp-json works exactly as I wish, as well as my WordPress instance on Digital Ocean.
How can a user whose blog is registered with wordpress.com enable their REST API?
add_action( 'rest_api_init', function () {
$namespace = 'aroma_api';
register_rest_route( $namespace, '/get_signin', array (
'methods' => 'POST',
'callback' => 'get_singnin_data',
));
} );
function get_singnin_data($data)
{
global $wpdb;
$resultdata = array();
$resultdata['message'] = 'Login SuccessFull';
return $resultdata;
}

Resources