Create a simple GET endpoint

add_action( 'rest_api_init', function () {
  register_rest_route( 'my_endpoint', '/do_something', array(
    'methods' => 'GET',
    'callback' => '\MyNamespace\my_endpoint_callback',
    'permission_callback' => '__return_true'                //Use this for a public endpoint
  ) );
} );

function my_endpoint_callback ($Request = null)
{
  $Name = "";
  if (isset($_REQUEST['name']))
    $Name= $_REQUEST['name'];

  $Output = array();
  $Output['Result'] = "Hi there: $Name";

  echo json_encode($Output);
}
//You can use these URLs to access it (either, both do same thing):
//https://my_domain.com/?rest_route=/my_endpoint/do_something&name=John
//https://my_domain.com/wp-json/my_endpoint/do_something&name=John

Create a simple POST endpoint

add_action( 'rest_api_init', function () {
  register_rest_route( 'my_endpoint', '/do_something', array(
    'methods' => 'POST',
    'callback' => '\MyNamespace\my_endpoint_callback',
    'permission_callback' => '__return_true'
  ) );
} );

function my_endpoint_callback ($Request = null)
{
  $Parameters = $Request->get_params();     //get_params() returns all parameters for the request as an array
  //var_dump($Parameters);

  $SomeFieldValue = '';
  if (isset($Parameters['some_field']))
    $SomeFieldValue = sanitize_text_field($Parameters['some_field']);

  $Output = array();
  $Output['Result'] = "success";

  echo json_encode($Output);
}
//You can use these URLs to access it (either, both do same thing):
//https://my_domain.com/?rest_route=/my_endpoint/do_something
//https://my_domain.com/wp-json/my_endpoint/do_something

Authenticating the current user in a call to the endpoint

A REST api request is by default non-authenticated. If you want to use things like get_current_user_id() in your endpoint handling code, you need to pass a nonce to the endpoint when calling it.

If using POST then ensure you include a POST parameter named ‘_wpnonce’.

The value to put in it can be obtained using:

  $WpNonce = wp_create_nonce('wp_rest');      //Create a nonce for our REST api request

Debugging a POST endpoint

//To debug this endpoint: 
/*
  $WpNonce = wp_create_nonce('wp_rest');      //Create a nonce for our REST api request
  $HtmlOutput = <<<_END
    <form action="/?rest_route=/my_endpoint/do_something" method="POST">
      <input type="hidden" name="_wpnonce" value="$WpNonce" />
      
      <label>A value you need to pass:</label>
      <input type="text" name="MyValueName" style="width:200px;" value="">
      
      <input type="submit" value="Test Endpoint" />
    </form>
_END;
  echo $HtmlOutput
*/