How to create REST Based JSON API(how to modify the code below)?

try this:

if (isset($_GET['api'])) {
     if ($_GET['api'] == 'json' && isset($_GET['id'])) {
        $args = array(
            'p' => $_GET['id'],
             'post_type' => 'any'// ID of a page, post, or custom type
        );
        $query = new WP_Query($args); // $query is the WP_Query Object
        $post = $query->post;   // $post contains the post object   
        header("content-type: application/json");

        echo json_encode($post);
    }
     exit();
}

get post will retrieve a single post, it returns an array so it can go directly to json_encode, you will have to add to the URL “id=XX” where X is a number.

If you have the latest version of wordpress i recommend you to use the built-in api WP REST Api

error code: 523