REST API

Add CSV to Rest Endpoints

Last updated 3 weeks ago

PHP
// Add custom query var to REST API
function add_csv_query_var( $vars ) {
    $vars[] = 'csv';
    return $vars;
}
add_filter( 'query_vars', 'add_csv_query_var' );

// Modify REST API response based on the 'csv' query var
function custom_rest_api_response_format( $response, $post, $request ) {
    // Check if 'csv' query var is set
    if ( $request->get_param( 'csv' ) ) {
        // Convert data to CSV
        if ( ! empty( $response->data ) && is_array( $response->data ) ) {
            $csv_output = '';
            $headers = array_keys( $response->data[0] ); // Assuming all items have the same keys
            $csv_output .= implode( ',', $headers ) . "\n";

            foreach ( $response->data as $row ) {
                $csv_output .= implode( ',', $row ) . "\n";
            }

            // Return CSV formatted response
            $response->set_data( $csv_output );
            $response->header( 'Content-Type', 'text/csv' );
        }
    }
    return $response;
}
add_filter( 'rest_post_dispatch', 'custom_rest_api_response_format', 10, 3 );

// Example usage: Add the 'csv' query var to a specific endpoint (e.g., posts)
function modify_rest_api_for_csv_support() {
    register_rest_route( 'wp/v2', '/posts', array(
        'methods' => 'GET',
        'callback' => 'get_posts_callback',
        'permission_callback' => '__return_true',
    ) );
}

function get_posts_callback( $data ) {
    // Fetch posts or any custom data
    $posts = get_posts( array( 'numberposts' => 5 ) );
    $response = new WP_REST_Response( $posts );

    return $response;
}

add_action( 'rest_api_init', 'modify_rest_api_for_csv_support' );
PHP
// Add custom query vars for CSV, XML, and TXT
function add_custom_query_vars( $vars ) {
    $vars[] = 'csv';
    $vars[] = 'xml';
    $vars[] = 'txt';
    return $vars;
}
add_filter( 'query_vars', 'add_custom_query_vars' );

// Modify REST API response based on query vars (csv, xml, txt)
function custom_rest_api_response_format( $response, $post, $request ) {
    // Check if 'csv' query var is set
    if ( $request->get_param( 'csv' ) ) {
        // Convert data to CSV
        if ( ! empty( $response->data ) && is_array( $response->data ) ) {
            $csv_output = '';
            $headers = array_keys( $response->data[0] ); // Assuming all items have the same keys
            $csv_output .= implode( ',', $headers ) . "\n";

            foreach ( $response->data as $row ) {
                $csv_output .= implode( ',', $row ) . "\n";
            }

            // Return CSV formatted response
            $response->set_data( $csv_output );
            $response->header( 'Content-Type', 'text/csv' );
        }
    }

    // Check if 'xml' query var is set
    elseif ( $request->get_param( 'xml' ) ) {
        // Convert data to XML
        if ( ! empty( $response->data ) && is_array( $response->data ) ) {
            $xml_output = new SimpleXMLElement( '<root/>' );
            foreach ( $response->data as $item ) {
                $xml_item = $xml_output->addChild( 'item' );
                foreach ( $item as $key => $value ) {
                    $xml_item->addChild( $key, htmlspecialchars( $value ) );
                }
            }

            // Return XML formatted response
            $response->set_data( $xml_output->asXML() );
            $response->header( 'Content-Type', 'application/xml' );
        }
    }

    // Check if 'txt' query var is set
    elseif ( $request->get_param( 'txt' ) ) {
        // Convert data to plain text
        if ( ! empty( $response->data ) && is_array( $response->data ) ) {
            $txt_output = '';
            foreach ( $response->data as $item ) {
                $txt_output .= implode( ' ', $item ) . "\n";
            }

            // Return plain text formatted response
            $response->set_data( $txt_output );
            $response->header( 'Content-Type', 'text/plain' );
        }
    }

    return $response;
}
add_filter( 'rest_post_dispatch', 'custom_rest_api_response_format', 10, 3 );

// Example usage: Add the 'csv', 'xml', and 'txt' query vars to a specific endpoint (e.g., posts)
function modify_rest_api_for_multiple_formats() {
    register_rest_route( 'wp/v2', '/posts', array(
        'methods' => 'GET',
        'callback' => 'get_posts_callback',
        'permission_callback' => '__return_true',
    ) );
}

function get_posts_callback( $data ) {
    // Fetch posts or any custom data
    $posts = get_posts( array( 'numberposts' => 5 ) );
    $response = new WP_REST_Response( $posts );

    return $response;
}

add_action( 'rest_api_init', 'modify_rest_api_for_multiple_formats' );

Tags: #REST API, #WordPress

All code snippets are licensed GPLv2 or later unless otherwise stated.