Basically what I need is to get category_name and parent_category_name for each post in response for /wp-json/wp/v2/posts
Under categories it only returns array of category IDs. That's not an option since there is a lot of categories and subcategories to map all that stuff.
With parameter _embed I can get "wp:term" but it's not exactly what I need. It returns arrays of categories and tags both combined and sometimes it won't return the parent category.
Any solutions? Should I keep going on through the documentation or is there any function to extend the WordPress REST API response?
There are quite a few ways to manipulate the WP Rest API with the information you need.
One way would be to filter the post object in REST directly, using the rest_prepare_{$post_type} filter
Another would be to register a new "REST field" with the register_rest_field function.
Using the first one, you could do something as simple as getting the category names and dropping them in as a new data field:
add_filter( 'rest_prepare_post', 'my_filter_post', 10, 3 );
function my_filter_post( $data, $post, $context ){
// Does this have categories?
if( !empty($data->data['categories']) ){
// Loop through them all
foreach( $data->data['categories'] as $category_id ){
// Get the actual Category Object
$category = get_category( $category_id );
if( $category->parent == 0 ){
// "top level" category
$data->data['parent_category'] = $category->name;
} else {
// some child level category
$data->data['child_category'] = $category->name;
}
}
}
return $data;
}
Using the REST field option would look something like this WPSE answer, though you'd of course need to iterate over the categories to see which is the parent and which is the child, etc.
In either case, you may need to adjust the logic and use something like the get_ancestors() function or one of the many "get hierarchical cat/terms" answers, especially if you've got more than a "parent > child" relationship, or multiple levels of categories on each post - but rest_prepare_{$post_type} or register_rest_field should be able to get your desired result pretty easily.