wrapper that receives an api hit and creates json or a file based on market and product

Home » Snippets » wrapper that receives an api hit and creates json or a file based on market and product
0

Created with:

Visibility: 

public

Creator: Michael Libidinsky

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

<?php

namespace WPTurbo;

use WP_Error;

function wpturbo_api_handler() {
    $market = isset( $_GET['market'] ) ? sanitize_text_field( $_GET['market'] ) : '';
    $product = isset( $_GET['product'] ) ? sanitize_text_field( $_GET['product'] ) : '';

    if ( empty( $market ) || empty( $product ) ) {
        wp_send_json_error( 'Market and product parameters are required.', 400 );
        return;
    }

    // Simulate fetching data based on market and product
    $data = [
        'market' => $market,
        'product' => $product,
        'price' => 19.99,
        'availability' => 'In stock',
    ];

    // Determine the response format
    $format = isset( $_GET['format'] ) ? sanitize_text_field( $_GET['format'] ) : 'json';

    if ( 'json' === $format ) {
        wp_send_json_success( $data );
    } elseif ( 'file' === $format ) {
        $filename = "{$market}_{$product}.txt";
        header( 'Content-Type: text/plain' );
        header( 'Content-Disposition: attachment; filename=' . $filename );
        echo "Market: {$market}nProduct: {$product}nPrice: {$data['price']}nAvailability: {$data['availability']}";
        exit;
    } else {
        wp_send_json_error( 'Invalid format specified. Use "json" or "file".', 400 );
    }
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'wpturbo/v1', '/data', [
        'methods' => 'GET',
        'callback' => 'WPTurbowpturbo_api_handler',
    ]);
});
				

This structure follows the best practices for WordPress development, ensuring readability, security, and maintainability.

Register an account to save your snippets or go Pro to get more features.