WordPress already has an API you can extend, and a class for querying posts!
For example:
// when the rest_api_init action/event happens
add_action( 'rest_api_init', function () {
// register a new endpoint
register_rest_route( 'mohnish/v1', '/posts/', array(
'methods' => 'GET',
'callback' => 'mohnish_awesome_func', // that calls this function
) );
} );
// this is whats called when something hits the endpoint
function mohnish_awesome_func( WP_REST_Request $request ) {
// grab the parameters
$category = $request->get_param( 'category' );
$tag = $request->get_param( 'tag' );
// run the query to fetch the data
$q = new WP_Query( [
'category_name' => $category,
'tag' => $tag,
// etc...
]);
$results = []; // an empty array to hold our results
if ( $q->have_posts() ) {
while( $q->have_posts() ) {
$q->the_post();
// add a new result to the list
$results[] = [
'title' => get_the_title(),
// etc...
];
}
}
return $results; // the REST API will automagically convert this to json
}
This would let you write URLs such as:
https://example.com/wp-json/mohnish/v1/posts/?category=foo&tag=bar
And get a JSON data structure back with information.
Luckily, Core already has a posts endpoint that does a lot of what you want to do at /wp-json/wp/v2/posts
, here’s an example with a live site:
curl http://demo.wp-api.org/wp-json/wp/v2/posts
You can see a full schema of what it returns here with examples on deleting posting and grabbing individual posts here, as well as a handbook detailing how to use all its features and extend it