achilles283
6/6/2018 - 6:51 AM

WordPress REST API recipes

WordPress REST API recipes

<?php

/**
 * Really simple GET request
 */
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) {
	register_rest_route( '/custom-namespace/v1', '/no-param', [
		'methods'  => 'GET',
		'callback' => function ( WP_REST_Request $request ) {
			if ( $throw_error = false ) {
				return new WP_Error( 'some-error-code', 'There was an error', [
					'heres' => 'some',
					'error' => 'data'
				] );
			} else {
				return new WP_REST_Response( [
					'here' => 'is',
					'some' => 'data'
				], 200 );
			}

		}
	] );
} );


/**
 * Really simple GET request that accepts an integer as a parameter/arg
 */
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) {
	register_rest_route( '/custom-namespace/v1', '/numeric-param/(?P<numeric_param>[\d]+)', [
		'args' => [
			'numeric_param' => [
				'description' => __( 'Some numberic parameter' ),
				'type'        => 'integer'
			],
		],
		[
			'methods'  => 'GET',
			'callback' => function ( WP_REST_Request $request ) {
				if ( $throw_error = false ) {
					return new WP_Error( 'some-error-code', 'There was an error', [
						'heres' => 'some',
						'error' => 'data'
					] );
				} else {
					return new WP_REST_Response( [
						'here'  => 'is',
						'some'  => 'data',
						'using' => 'provided',
						'arg'   => $request->get_param( 'numeric_param' )
					], 200 );
				}
			}
		]
	] );
} );


/**
 * Really simple GET request that accepts a string as a parameter/arg
 */
add_action( 'rest_api_init', function ( WP_REST_Server $wp_rest_server ) {
	register_rest_route( '/custom-namespace/v1', '/string-param/(?P<string_param>[a-zA-Z0-9_-]+)', [
		'args' => [
			'string_param' => [
				'description' => __( 'Some string arg' ),
				'type'        => 'string'
			],
		],
		[
			'methods'  => 'GET',
			'callback' => function ( WP_REST_Request $request ) {
				if ( $throw_error = false ) {
					return new WP_Error( 'some-error-code', 'There was an error', [
						'heres' => 'some',
						'error' => 'data'
					] );
				} else {
					return new WP_REST_Response( [
						'here'  => 'is',
						'some'  => 'data',
						'using' => 'provided',
						'arg'   => $request->get_param( 'string_param' )
					], 200 );
				}
			}
		]
	] );
} );