ampproject / samples

Apache License 2.0
444 stars 191 forks source link

API call in amp pages when page load #89

Open jeenamanuel opened 7 years ago

jeenamanuel commented 7 years ago

How can i make an api call in my amp page. api response is in json format

grupie001 commented 6 years ago

I think I am looking for something similar. I would like to connect this "sample" to my wordpress api and useless WP just as headless Backend and this "sample" as front. Any suggestion how to do it?

nisargrthakkar commented 5 years ago

Yes, I am looking for the same. Rest API call in AMP page.

westonruter commented 5 years ago

Do you mean requesting data from the WordPress REST API? If using the official AMP plugin for WordPress, the necessary CORS headers are added automatically. The headers are added automatically by AMP_HTTP::send_cors_headers() whenever the request includes the __amp_source_origin query param, which AMP adds automatically. So as long as WordPress is handling the fetch request, then the necessary CORS headers should all be supplied automatically.

So you just use the rest_url() that WordPress provides. For example, here is a shortcode that shows the latest posts:

add_shortcode(
    'amp_latest_posts',
    function() {
        $endpoint = rest_url( 'wp/v2/posts' );

        /*
         * Enqueue scripts for when shortcode is used on non-AMP pages. These are unnecessary on AMP pages because the
         * post-processor will automatically add them when it encounters <amp-list>.
         */
        wp_enqueue_script( 'amp-list' );
        wp_enqueue_script( 'amp-mustache' );

        ob_start();
        ?>
        <amp-list src="<?php echo esc_url( $endpoint ); ?>" items="." layout="fixed-height" height="300" width="auto">
            <template type="amp-mustache">
                <div>
                    <a href="{{link}}">{{title.rendered}}</a>
                </div>
            </template>
        </amp-list>
        <?php
        return ob_get_clean();
    }
);