How do I create a custom api endpoint?

Solution:

You can use parse_request hook for creating end point, below is the example from one of my plugin

// this example creates endpoint like http://emerico.in/api/v2

add_action('parse_request', 'endpoint', 0);
add_action('init', 'add_endpoint');

/**
 * @param null
 * @return null
 * @description Create a independent endpoint
 */
function endpoint()
{
    global $wp;

    $endpoint_vars = $wp->query_vars;

    // if endpoint
    if ($wp->request == 'api/v2') {

        // Your own function to process end pint
        $this->processEndPoint($_REQUEST);

        // After all redirect to home page
        wp_redirect(home_url());
        exit;
    } elseif (isset($endpoint_vars['tracking']) && !empty($endpoint_vars['tracking'])) {
        $request = [
            'tracking_id' => $endpoint_vars['tracking']
        ];

        $this->processEndPoint($request);
    } elseif (isset($_GET['utm_source']) && !empty($_GET['utm_source'])){
        $this->processGoogleTracking($_GET);
    }
}

/**
 * @param null
 * @return null
 * @description Create a permalink endpoint for projects tracking
 */
function add_endpoint()
{

    add_rewrite_endpoint('tracking', EP_PERMALINK | EP_PAGES, true);

}