# Example Custom REST API Endpoint

> Registers a read-only endpoint at /wp-json/wpide/v1/latest that returns your latest posts in a compact format, as a starting point for your own API routes.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: rest-api, api, json, headless
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/dev-custom-rest-route/

## Code

```php
add_action( 'rest_api_init', function () {
    register_rest_route( 'wpide/v1', '/latest', array(
        'methods'             => WP_REST_Server::READABLE,
        'permission_callback' => '__return_true', // Public, read-only data.
        'args'                => array(
            'count' => array(
                'default'           => 5,
                'sanitize_callback' => 'absint',
                'validate_callback' => function ( $value ) {
                    return is_numeric( $value ) && $value >= 1 && $value <= 20;
                },
            ),
        ),
        'callback'            => function ( WP_REST_Request $request ) {
            $posts = get_posts( array(
                'numberposts' => (int) $request->get_param( 'count' ),
                'post_status' => 'publish',
            ) );

            return rest_ensure_response( array_map( function ( $post ) {
                return array(
                    'id'      => $post->ID,
                    'title'   => get_the_title( $post ),
                    'url'     => get_permalink( $post ),
                    'date'    => get_post_time( 'c', true, $post ),
                    'excerpt' => wp_strip_all_tags( get_the_excerpt( $post ) ),
                    'image'   => get_the_post_thumbnail_url( $post, 'medium' ) ? get_the_post_thumbnail_url( $post, 'medium' ) : null,
                );
            }, $posts ) );
        },
    ) );
} );
```

## Notes

Change the namespace, route and callback to build your own endpoint. Make permission_callback stricter for anything that is not public.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Example Custom REST API Endpoint" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
